在R中的data.table中添加一个空列表作为值

squ*_*bug 2 r data.table

我在R中有一个data.table,其中一列对应一个字符串列表,如下所示:

DT <- data.table(c1 = 1:3, 
                 c2 = as.list(c("bob",NA,"mary")), 
                 c3 = as.list(c(NA,"joe",NA)))
Run Code Online (Sandbox Code Playgroud)

我想用空列表替换NA值,因为我后来连接列c2和c3,使用:

DT[, combined := list(list(unlist(union(c2,c3)))), by=c1]
Run Code Online (Sandbox Code Playgroud)

这给了我

DT$combined
   [[1]] bob,NA
   [[2]] NA,joe
   [[3]] mary,NA
Run Code Online (Sandbox Code Playgroud)

而不是期望的

DT$combined
   [[1]] bob
   [[2]] joe
   [[3]] mary
Run Code Online (Sandbox Code Playgroud)

我可以通过将NA转换为空列表来获得所需的结果,这就是我的问题所在:如何以优雅的方式进行操作?

我可以使用数据框语法摆脱NA:

DT$c2[is.na(DT$c2)] <- list(list())
Run Code Online (Sandbox Code Playgroud)

但是,因为我正在使用数据表,并且它们应该比这更好,我想做类似的事情

set(DT, DT[,.I[is.na(c2)]], "c2", value= list(list()))
Run Code Online (Sandbox Code Playgroud)

哪个R吐出以下错误:

Error in set(DT, DT[, .I[is.na(c2)]], "c2", value = list(list())) : 
RHS of assignment to existing column 'c2' is zero length but not   NULL. 
If you intend to delete the column use NULL. Otherwise, the RHS must have length > 0; 
e.g., NA_integer_. If you are trying to change the column type to be an empty list column then, 
as with all column type changes, provide a full length RHS vector such as 
vector('list',nrow(DT)); i.e., 'plonk' in the new column.
Run Code Online (Sandbox Code Playgroud)

我只是在寻找一种更好的方法来使用data.tables.

edd*_*ddi 7

添加明确NULLlist(list()):

DT[is.na(c2), c2 := .(list(NULL))]

# or loop over the relevant columns
for (col in c('c2', 'c3')) DT[is.na(get(col)), (col) := .(list(NULL))]
Run Code Online (Sandbox Code Playgroud)