我在R中有一个data.table,其中一列对应一个字符串列表,如下所示:
DT <- data.table(c1 = 1:3,
c2 = as.list(c("bob",NA,"mary")),
c3 = as.list(c(NA,"joe",NA)))
我想用空列表替换NA值,因为我稍后使用以下方法连接列c2和c3:
DT[, combined := list(list(unlist(union(c2,c3)))), by=c1]
给了我
DT$combined
[[1]] bob,NA
[[2]] NA,joe
[[3]] mary,NA
而不是所需的
DT$combined
[[1]] bob
[[2]] joe
[[3]] mary
我可以通过将NAs转换为空列表来获得所需的结果,这就是我的问题所在:如何以优雅的方式进行操作?
我可以使用数据帧语法删除NA:
DT$c2[is.na(DT$c2)] <- list(list())
但是,因为我使用数据表,并且它们应该比这更好,我想做类似的事情
set(DT, DT[,.I[is.na(c2)]], "c2", value= list(list()))
哪个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.
我正在寻找更好的方法来使用data.tables。
答案 0 :(得分:7)
向NULL
list(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))]