简体   繁体   English

将列表分配给data.table

[英]Assign a list to data.table

In the next code I create a data.table and input some stuff: 在下面的代码中,我创建一个data.table并输入一些内容:

library(data.table)
int.tables <- c( "Sheet_A","TBL 002"
                 ,"Sheet_B", "TBL 001"
                 ,"Sheet_B", "TBL 004"
                 ,"Sheet_C", "TBL 009")

int.tables<-data.table(matrix(int.tables,ncol = 2,byrow = T)) 
setnames(int.tables,c("sheet","table"))

level_Sheet_A <- list(   "Level_1",   "Level_2",   "Level_3" )

int.tables[sheet == "Sheet_B" & table %in% c("TBL 001", "TBL 004")
           , legend_levels := .(.(level_Sheet_A))]

However, in order to correctly input a list as a whole element per row requires the weird code .(.()) in the last line. 但是,为了正确地将列表作为每行的整个元素输入,需要在最后一行添加怪异的代码.(.()) Otherwise, the output will enumerate the elements of level_sheet_A along the rows. 否则,输出将沿行枚举level_sheet_A的元素。 Is there a better/cleaner way to do it? 有更好/更清洁的方法吗?

I would write it like this: 我会这样写:

int.tables <- data.frame(sheet = c( "Sheet_A", "Sheet_B", "Sheet_B","Sheet_C"),
                         table = c("TBL 002","TBL 001", "TBL 004", "TBL 009"))

index  <- int.tables$sheet == c("Sheet_B") & 
          int.tables$table %in% c("TBL 001", "TBL 004")

int.tables$legend_levels[index] <- list(c("Level_1", "Level_2", "Level_3" ))

Then you remove your dependency on data.table and avoid the unnecessary matrix construction. 然后,删除对data.table的依赖,避免不必要的矩阵构造。 If you want to can add the class data.table to get the pretty printing at the end 如果要添加类data.table以获得最后的漂亮打印效果

class(int.tables) <- c("data.table", class(int.tables))

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

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