首页 > 解决方案 > Assign a list to data.table

问题描述

In the next code I create a data.table and input some stuff:

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. Is there a better/cleaner way to do it?

标签: rdata.table

解决方案


我会这样写:

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" ))

然后你删除你的依赖data.table并避免不必要的矩阵构造。如果您想添加类data.table以在最后获得漂亮的打印

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

推荐阅读