【发布时间】:2011-09-17 22:42:44
【问题描述】:
用两个数据框df1和df2
定义一个列表datsdats <- list( df1 = data.frame(a=sample(1:3), b = sample(11:13)),
df2 = data.frame(a=sample(1:3), b = sample(11:13)))
> dats
$df1
a b
1 2 12
2 3 11
3 1 13
$df2
a b
1 3 13
2 2 11
3 1 12
我想在每个数据框中删除变量 a。接下来,我想从外部数据帧中添加一个带有每个数据帧 id 的变量,例如:
ids <- data.frame(id=c("id1","id2"),df=c("df1","df2"))
> ids
id df
1 id1 df1
2 id2 df2
为了删除不必要的变量,我尝试了这个没有运气:
> dats <- lapply(dats, function(x) assign(x, x[,c("b")]))
> Error in assign(x, x[, c("b")]) : invalid first argument
也不知道怎么添加id。
我也试过了,也许更合适:
> temp <- lapply(dats, function(x) subset(x[1], select=x[[1]]$b))
Error in x[[1]]$b : $ operator is invalid for atomic vectors
我感到困惑的是str(out[1]) 返回一个列表,str(out[[1]]) 返回一个数据框。我认为这可能与它有关。
【问题讨论】:
-
如果您不同意我的编辑,请随时回滚。我喜欢这个问题。
标签: r lapply data-manipulation data-management