简体   繁体   English

在R中的data.table的每一行列出具有NA值的列

[英]List columns with NA values for each row of a data.table in R

I'd like to add a column to a data.table object which lists the column names that are NA for that row. 我想在data.table对象中添加一列,该对象列出该行的NA名称。 For example let's say I have the following data.table: 例如,假设我有以下data.table:

dt <- data.table(a = c(1, 2, 3, NA), 
                 b = c(1, 2, NA, NA), 
                 c = c(NA, 2, NA, 4))
    a  b  c        
1:  1  1 NA        
2:  2  2  2        
3:  3 NA NA        
4: NA NA  4

I'd like to add a column with these values, resulting in the below data.table: 我想用这些值添加一列,得到以下data.table:

dt[, na.cols := c("c", "", "b,c", "a,b")]
    a  b  c na.cols        
1:  1  1 NA       c
2:  2  2  2        
3:  3 NA NA     b,c
4: NA NA  4     a,b

How can I add this column dynamically? 如何动态添加此列?

Here is an approach that will avoid using apply on a data.table (which coerces to matrix internally) 这是一种避免在data.table上使用applydata.table在内部矩阵化)的方法

dt[, na.cols := gsub('(^,+)|(,+$)','',do.call(paste, c(lapply(seq_along(.SD), function(x) ifelse(is.na(.SD[[x]]),names(.SD)[x],'')), sep=',')))]
#     a  b  c na.cols
# 1:  1  1 NA       c
# 2:  2  2  2        
# 3:  3 NA NA     b,c
# 4: NA NA  4     a,b

You could do it this way: 您可以这样进行:

dt[, na.cols := 
   apply(dt, 1, function(row) paste(names(row)[which(is.na(row))],
                                    collapse=","))]  

Details: basically, you're using apply along margin 1 (ie along the rows) and then, for each row, pasting together column names that are NA . 详细信息:基本上,您将沿边margin 1 (即沿行)使用Apply,然后针对每一行将NA列名粘贴在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM