Thomas Langkamp
Thomas Langkamp

Reputation: 153

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})

Upvotes: 2

Views: 122

Answers (2)

Gavin Simpson
Gavin Simpson

Reputation: 174853

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

Upvotes: 3

joran
joran

Reputation: 173657

How about something like this:

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

Upvotes: 1

Related Questions