Convert list of data frames into two lists

I have got the following list of data frames:

> l = list(df1 = data.frame(x=1:4, y=c("A","B","B","A")), df2 = data.frame(x=6:9, y=c("A","B","A","A")))
> l
$df1
  x y
1 1 A
2 2 B
3 3 B
4 4 A

$df2
  x y
1 6 A
2 7 B
3 8 A
4 9 A

I would like to generate two lists A and B without a for loop, that look like this:

> A = list(df1 = data.frame(x=c(1,4), y=c("A","A")), df2 = data.frame(x=c(6,8,9), y=c("A","A","A")))
> A
$df1
  x y
1 1 A
2 4 A

$df2
  x y
1 6 A
2 8 A
3 9 A
> B = list(df1 = data.frame(x=c(2,3), y=c("B","B")), df2 = data.frame(x=c(7), y=c("B")))
> B
$df1
  x y
1 2 B
2 3 B

$df2
  x y
1 7 B

Basically, it needs to separate the data frames based on column y.

Thank you!
Nicola

Here's one possible approach using lapply:

f <- function(input_list, selection = "A"){
  return(lapply(input_list, function(df) df[df$y == selection,]))
}
A <- f(l, "A")
B <- f(l, "B")

Edit: Switched argument names. While it also works, using list and which as argument names is probably not a good practice.

1 Like

I have also found this solution:

A = lapply(l, function(df) dplyr::filter(df, y == "A"))
B = lapply(l, function(df) dplyr::filter(df, y == "B"))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.