R:在列表中应用函数
我有一个包含 2000 个组件数据帧的大列表。以下只是一个示例:
set.seed(1234)
mydf1 <- data.frame(v = c(1:5), x = rnorm(5, 0.06, 0.01))
mydf2 <- data.frame(v = c(1:5), x = rnorm(5, 0.06, 0.01))
mydf3 <- data.frame(v = c(1:5), x = rnorm(5, 0.06, 0.01))
mylist <- list(mydf1, mydf2, mydf3)
mylist
[[1]]
v x
1 1 0.03792934
2 2 0.05277429
3 3 0.06084441
4 4 0.02654302
5 5 0.05429125
[[2]]
v x
1 1 0.05506056
2 2 0.04425260
3 3 0.04453368
4 4 0.04435548
5 5 0.04109962
[[3]]
v x
1 1 0.04522807
2 2 0.04001614
3 3 0.04223746
4 4 0.05064459
5 5 0.05959494
我想按小于 << 的 x 值对整个列表进行子集化。 0.05(在每个列表组件内)并创建一个新列表。
mylist1 <- mylist[ which ( x < 0.05),]
不起作用......请帮忙。谢谢...
I have a large list with 2000 component dataframes. The following is just an example:
set.seed(1234)
mydf1 <- data.frame(v = c(1:5), x = rnorm(5, 0.06, 0.01))
mydf2 <- data.frame(v = c(1:5), x = rnorm(5, 0.06, 0.01))
mydf3 <- data.frame(v = c(1:5), x = rnorm(5, 0.06, 0.01))
mylist <- list(mydf1, mydf2, mydf3)
mylist
[[1]]
v x
1 1 0.03792934
2 2 0.05277429
3 3 0.06084441
4 4 0.02654302
5 5 0.05429125
[[2]]
v x
1 1 0.05506056
2 2 0.04425260
3 3 0.04453368
4 4 0.04435548
5 5 0.04109962
[[3]]
v x
1 1 0.04522807
2 2 0.04001614
3 3 0.04223746
4 4 0.05064459
5 5 0.05959494
I want to subset this whole list by value of x which is less than < 0.05 (within each list components) and creat a new list.
mylist1 <- mylist[ which ( x < 0.05),]
Does not work....please help. Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实现此目的的一种方法是使用
lapply
并将子集代码作为函数。由于
mydf1[mydf1$x<0.05, ]
将返回您感兴趣的子集,因此代码变为:One way of doing this is to use
lapply
with your subset code as the function.Since
mydf1[mydf1$x<0.05, ]
will return the subset that you are interested in, the code becomes:lapply(mylist, 函数(y) 子集(y, x < 0.05))
lapply(mylist, function(y) subset(y, x < 0.05))
您可能想使用 plyr 包的 llply 函数。
You might want to use llply function of plyr package.
当您开始使用哪个函数的问题时,我只是像其他人一样将 which 与 lappy 一起使用
lapply(mylist, function(y) y[which(y$x>0.05),])
As you started the question with using which function, I just used the which with lappy like others
lapply(mylist, function(y) y[which(y$x>0.05),])