Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: applying function inside a list

Tags:

dataframe

r

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...

like image 248
John Clark Avatar asked Jan 18 '23 18:01

John Clark


2 Answers

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)
like image 76
Andrie Avatar answered Jan 21 '23 13:01

Andrie


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

like image 41
Brandon Bertelsen Avatar answered Jan 21 '23 13:01

Brandon Bertelsen