简体   繁体   中英

Erasing specific rows of multiple dataframes within a list

Lets suppose I have such a list including 3 dataframes named 1, 3 and 4:

        1                   3           4  
1   A   c(2, 1, 3, 1, 2)    c(1, 1, 2)  c(1, 1)
2   B   c(1, 1, 1, 3, 2)    c(2, 1, 2)  c(2, 1)

The dataframes have all the same columns (A and B) but different counts of rows as you see. How do I erase the rows which have values < 2 in column B for all dataframes in the list?

I tried lapply with any:

list <- lapply(list, function(x) {x <- any(x[,c(2)] < 2);x})

Judicious use of lapply() and simple subsetting is as good as any approach. Using your data in l :

l <- list("1" = data.frame(A = c(2, 1, 3, 1, 2), B = c(1, 1, 1, 3, 2)),
          "3" = data.frame(A = c(1,1,2), B = c(2,1,2)),
          "4" = data.frame(A = c(1,1), B = c(2,1)))

This does what you want

lapply(l, function(x) x[x$B >= 2,])

giving:

> lapply(l, function(x) x[x$B >= 2,])
$`1`
  A B
4 1 3
5 2 2

$`3`
  A B
1 1 2
3 2 2

$`4`
  A B
1 1 2

How about something like this:

lst <- lapply(lst, function(x) {subset(x, B >= 2)})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM