【问题标题】:Replace numeric(0) with NAs in all lists in a column of lists in r在 r 中的列表列中的所有列表中将 numeric(0) 替换为 NA
【发布时间】:2018-08-10 15:27:17
【问题描述】:

我在存储列表的数据框中有一列。下面是一个例子:

           col
1   9
2   8, 8, 8, 5
3   1, 8, 10, 4
4   3, 6, 1, 6
5   9, 9, 10, 4
6   8, 8, 9, 2
7   6, 10, 4, 7
8   6, 1, 5, 9
9   4, 7, 5, 10
10  7, 9, 2, 5

这是我用来生成上述示例的代码:

set.seed(123)
example <- data.frame(matrix(NA_real_, nrow=10, ncol=1))
colnames(example) <- "col"
for(y in 1:10) {
  example$col[y] <- list(c(c(sample(1:10,1)),c(sample(1:10,1)),c(sample(1:10,1)),c(sample(1:10,1))))
}

example$col[1] <- list(c(9))

我想从我的数据框的这一列中的所有这些列表中删除所有出现的数字 9,以获得如下内容:

           col
1   NA
2   8, 8, 8, 5
3   1, 8, 10, 4
4   3, 6, 1, 6
5   10, 4
6   8, 8, 2
7   6, 10, 4, 7
8   6, 1, 5
9   4, 7, 5, 10
10  7, 2, 5

而不是这个,我目前正在使用example$col &lt;- lapply(example$col, function(x){ x[x != 9] })

           col
1   numeric(0)
2   8, 8, 8, 5
3   1, 8, 10, 4
4   3, 6, 1, 6
5   10, 4
6   8, 8, 2
7   6, 10, 4, 7
8   6, 1, 5
9   4, 7, 5, 10
10  7, 2, 5

如何将numeric(0) 替换为NA_real_ 并且仍然能够删除所有9?

【问题讨论】:

    标签: r list dataframe na


    【解决方案1】:

    您可以同时执行这两种操作,删除 9将单个 9 更改为 NA_real_,一步中使用 if 语句。

    example$col <- lapply(example$col, function(x) {
        if(length(x) == 1L && x == 9) NA_real_ else x[x != 9]
    })
    
    example
    #             col
    # 1            NA
    # 2      10, 1, 6
    # 3   6, 5, 10, 5
    # 4       7, 6, 2
    # 5   3, 1, 4, 10
    # 6      7, 7, 10
    # 7    7, 8, 6, 6
    # 8  3, 2, 10, 10
    # 9    7, 8, 1, 5
    # 10   8, 3, 4, 3
    

    【讨论】:

      【解决方案2】:

      像这样修改你的lapply 声明

      lapply(example$col, function(x){ y <- x[x != 9]; if(length(y) < 1) { y <- NA }; y })
      

      作为自己的功能 - 使将来更容易修改

      remove_num <- function(vec, num) {
         x <- vec[vec != num]
         if (length(x) < 1) { x <- NA }
         x
      }
      
      lapply(example$col, remove_num, 9)
      

      【讨论】:

        猜你喜欢
        • 2021-07-08
        • 1970-01-01
        • 1970-01-01
        • 2016-12-11
        • 2021-11-05
        • 1970-01-01
        • 2011-11-08
        • 2019-07-22
        相关资源
        最近更新 更多