【问题标题】:Replace NA values with corresponding non NA values in side column [duplicate]用侧列中相应的非 NA 值替换 NA 值[重复]
【发布时间】:2019-06-27 18:40:54
【问题描述】:

我有一个data.table,名为 temp:

PID PID_Gen 
a   NA   
c   c1
b   NA
d   d1

下面评估PID_Gen 是否为NULL,在这种情况下分配PID 的值。

temp$result <- future_sapply(temp$PID_Gen, 
                             FUN = function(x) if(is.na(x)) {temp$PID})

问题是它溢出了内存。

我可以使用其他替代方法吗?

【问题讨论】:

  • 这个工作吗:temp$result &lt;- ifelse(is.na(temp$PID_Gen), as.character(temp$PID), as.character(temp$PID_Gen))

标签: r data.table


【解决方案1】:

这是我的方法:

temp <- read.table(text = "PID PID_Gen 
                   a   NA   
                   c   c1
                   b   NA
                   d   d1", header = TRUE, stringsAsFactors = FALSE)
temp$result <- ifelse(is.na(temp$PID_Gen), temp$PID, temp$PID_Gen)

【讨论】:

    【解决方案2】:

    这是你想要的结果吗?

    df <- read.table(text = "PID PID_Gen 
    a   NA   
    c   c1
    b   NA
    d   d1", header = TRUE, stringsAsFactors = FALSE)
    
    df$PID_Gen[is.na(df$PID_Gen)] <- df$PID[is.na(df$PID_Gen)]
    
    print(df)
    #>   PID PID_Gen
    #> 1   a       a
    #> 2   c      c1
    #> 3   b       b
    #> 4   d      d1
    

    reprex package (v0.2.1.9000) 于 2019 年 2 月 3 日创建

    【讨论】:

      猜你喜欢
      • 2011-12-05
      • 2021-06-28
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多