Reputation: 1363
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?
Upvotes: 0
Views: 420
Reputation: 1234
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. If you want to can add the class data.table
to get the pretty printing at the end
class(int.tables) <- c("data.table", class(int.tables))
Upvotes: 1