【问题标题】:How to replace NAs with values from another column in data.table (Example given)?如何用 data.table 中另一列的值替换 NA(给出的示例)?
【发布时间】:2020-02-19 09:52:00
【问题描述】:

DT 是 data.table,我想用访问列中的值替换 NA,而 Expected_DT 是所需的 DT。

DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(NA,45,56,78),visits=c(14,45,56,78))

name hour count visits
1:    x    1    NA     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78

这就是我想要的

Expected_DT<-data.table(name=c("x","x","x","x"),hour=1:4,count=c(14,45,56,78),visits=c(14,45,56,78))


   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78

【问题讨论】:

  • count &gt;= visits 总是正确的吗?

标签: r data.table


【解决方案1】:

几个选项:

1) 使用fcoalesce

DT[, count := fcoalesce(visits, count)]

2) 使用is.na:

DT[is.na(count), count := visits]

3) 使用fifelse:

DT[, count := fifelse(is.na(count), visits, count)]

4) 使用 set 并使用 sindri_baldur 对 [[ 的评论以加快索引速度:

ix <- DT[is.na(count), which=TRUE]
set(DT, ix, "count", DT[["visits"]][ix])

【讨论】:

  • 可以通过将DT[ix, visits] 替换为DT[[c(4, ix)]] 来加速4)
  • @sindri_baldur。谢谢,这是我第一次看到这种语法。如果我没记错的话,如果有超过 1 个 NA,它将不起作用
  • 对不起,我的错!我认为替换将是DT[["visits"]][ix]。关键是data.table 有一些开销,所以使用 uber fast set() 所以如果直接提取一些值,使用列表语法会更快。
【解决方案2】:

使用data.table的解决方案:

DT[is.na(count),  count:=visits]

DT

返回:

   name hour count visits
1:    x    1    14     14
2:    x    2    45     45
3:    x    3    56     56
4:    x    4    78     78

【讨论】:

    【解决方案3】:

    一些基本的 R 解决方案

    • 使用ifelse
    DT <- within(DT, count <- ifelse(is.na(count),visits,count))
    
    • 使用rowSums
    DT <- within(DT, count <- rowSums(cbind(is.na(count)*visits,count),na.rm = TRUE))
    

    【讨论】:

      【解决方案4】:

      这是一个完整的 dplyr 版本,供其他用户使用:

      library(dplyr)
      
      DT %>%
          mutate(count = if_else(is.na(count), visits, count))
      
        name hour count visits
      1    x    1    14     14
      2    x    2    45     45
      3    x    3    56     56
      4    x    4    78     78
      

      【讨论】:

        猜你喜欢
        • 2022-07-15
        • 1970-01-01
        • 2015-07-16
        • 1970-01-01
        • 2016-03-08
        • 1970-01-01
        • 2019-08-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多