r - 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?
解决方案
我会这样写:
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))
推荐阅读
- apache-spark - Spark 不允许在同一 Spark SQL 查询中对同一数据源进行单独查询
- java - 慢跑。OpenGL。如何更新 VBO?
- python - 在两个时间戳之间创建 5 分钟的间隔
- jquery - 查询。$.get(url, callback) 不会触发回调
- python - python将输出写入csv文件
- java - 如何在此代码中显示负数阶乘
- syntax - 当verilog中处理器中的不同模块相反时如何声明输入和输出?
- c# - Zkteco 事件监听器在 ASP.NET Web 服务项目中不起作用
- functional-programming - 如何更新 SML 中的记录值?
- php - 谷歌服务器到服务器 OAuth2 PHP 示例不起作用