gpt4 book ai didi

r - 如何更新data.table中的现有列值?

转载 作者:行者123 更新时间:2023-12-04 23:02:17 25 4
gpt4 key购买 nike

我刚开始这个编程,很抱歉问这个简单的问题,但我被卡住了。

我有一个名为 s3 的 data.table:

s3:

ClaimID           dx      dxgroup
15nhbfcgcda 113.8 NA
15nhbfcgcda 156.8 NA
15nhbfcgcda 110.8 059
15nhbfcfssa 135.8 NA
15nhb4dfgda V70.3 NA
15nhbf644da 118.8 042

S3 有 30000 行。
  • 我想应用这个逻辑:
    If dxgroup = NA(
    If dx (fisrt 4 characters match with)= (2024, 2967, 9786,9788,8263)
    then dxgroup = (first 4 character of dx)
    else dx (fisrt 3 characters match with) = (V70, 042,897)
    then dxgroup = (first 3 character of dx)
    else dxgroup = dx
    )
  • 结果应该是这样的:
    ClaimID           dx      dxgroup
    15nhbfcgcda 113.8 113.8
    15nhbfcgcda 156.8 156.8
    15nhbfcgcda 110.8 059
    15nhbfcfssa 135.8 135.8
    15nhb4dfgda V70.3 V70
    15nhbf644da 118.8 042
  • 请指教 ?
  • 我道歉:这是我第一次在这里问问题,所以还不习惯。所以我做了这样的事情(如果这是正确的,我没有,我也有错误):

    sample4<-sample3[, dxgroup := { if (dxgroup == NA)

    • { if (substring(sample3$dx,1,4) == list (2501,2780,4151,5301,5751,6860,7807,7890,9898,9955,9970)) substring(sample3$dx,1,4)
    • else if (substring(sample3$dx,1,3) == list (042,493,682,850,V72)) substring(sample3$dx,1,3)
    • else if (substring(sample3$dx,1,4) == list (8540, 8541)) substring(sample3$dx,1,3)
    • else if (substring(sample3$dx,1,3) == list (043, 044)) 042
    • else if (substring(sample3$dx,1,3) == list (789) & substring(sample3$dx,1,3) != list(7891,7893,78930)) 7890
    • else if (substring(sample3$dx,1,4) == list (7865) & substring(sample3$dx,1,4) != list(78651,78652,78659)) 78650}
    • else sample3$dx}] Error in if (dxgroup == NA) { : missing value where TRUE/FALSE needed In addition: Warning message: In if (dxgroup == NA) { : the condition has length > 1 and only the first element will be used
  • 最佳答案

    你已经设置好了逻辑。

    请注意,使用 data.table(嗯,几乎所有 R ),您可以包装 j{curly brackets}括号中的最后一个语句是将分配的内容。例如:

    DT[,  dxgroup :=  { if (clause1)  
    {if (foo) beebar else bar}
    else chewybar
    }
    ]

    关于r - 如何更新data.table中的现有列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20406823/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com