我很好奇是否可以将[
orjoin
函数应用于 data.tables 列表。我可以让函数作用于列表的每个元素,但是在使用lapply
.
### Require data.table
require(data.table)
### Create master data.table
data <- data.table(id = letters[1:10], val = 1:10, key = 'id')
### Create data tables to be joined
a <- data.table(id = letters[1:10], height = rnorm(n = 10, mean = 150, sd = 10), key = 'id')
b <- data.table(id = letters[1:10], weight = rnorm(n = 10, mean = 140, sd = 20), key = 'id')
### Create a list of data tables to be joined
l <- list(a, b)
### Join data tables (Works)
`[`(l[[1]], data)
`[`(l[[2]], data)
### Apply join function to a list. Doesn't work. Why?
lapply(l, `[`, data)
Error in `[.default`(x, i) : invalid subscript type 'list'
这个错误让我想知道 R 如何区分何时[
用于连接,何时用于从对象中提取元素。例如:
### Extract first column from each data.table in 'l'
lapply(l, `[`, 1)