开发者

R: applying function inside a list

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开发者_StackOverflow中文版.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...


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, function(x)x[x$x<0.05, ])

[[1]]
  v          x
1 1 0.04792934
4 4 0.03654302

[[2]]
[1] v x
<0 rows> (or 0-length row.names)

[[3]]
[1] v x
<0 rows> (or 0-length row.names)


lapply(mylist, function(y) subset(y, x < 0.05))


You might want to use llply function of plyr package.

library(plyr)
mylist1 = llply(mylist, subset, x<0.05)

mylist1

[[1]]
  v          x
1 1 0.04792934
4 4 0.03654302

[[2]]
[1] v x
<0 rows> (or 0-length row.names)

[[3]]
[1] v x
<0 rows> (or 0-length row.names)


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),])

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜