I have a list of data frames that look as follows:
df1<- data.frame(x1=c("Ben","ABC","Alex","Tim", "Lisa", "MJ", "ABC"),
x2=c(3,NA,9,5,7,2,NA),
x3=c(3,NA,6,9,3,1,NA))
df2<- data.frame(x1=c("Alex","ABC","Tyler","Ben", "Lisa", "MJ", "ABC"),
x2=c(3,NA,2,5,7,2,NA),
x3=c(3,NA,6,5,3,2,NA))
df3<- data.frame(x1=c("Lisa","ABC","Tyler","Ben", "Lisa", "MJ", "ABC"),
x2=c(3,NA,9,5,7,2,NA),
x3=c(3,NA,6,9,3,1,NA))
df_list<-list(df1, df2, df3)
I want to delete all rows that contain the string "ABC" in all data frames in the list. In reality, my list of data frames contains many more data frames. Therefore, I do not want to perform the operation on each data frame seperately but directly to the list of data frames.
How could I do it? Thanks!
CodePudding user response:
You could use lapply
with grepl
like this:
lapply(df_list, \(x) x[!grepl("ABC", x$x1),])
#> [[1]]
#> x1 x2 x3
#> 1 Ben 3 3
#> 3 Alex 9 6
#> 4 Tim 5 9
#> 5 Lisa 7 3
#> 6 MJ 2 1
#>
#> [[2]]
#> x1 x2 x3
#> 1 Alex 3 3
#> 3 Tyler 2 6
#> 4 Ben 5 5
#> 5 Lisa 7 3
#> 6 MJ 2 2
#>
#> [[3]]
#> x1 x2 x3
#> 1 Lisa 3 3
#> 3 Tyler 9 6
#> 4 Ben 5 9
#> 5 Lisa 7 3
#> 6 MJ 2 1
Created on 2022-12-23 with reprex v2.0.2
CodePudding user response:
> lapply(df_list,function(x){x[x$x1!="ABC",]})
[[1]]
x1 x2 x3
1 Ben 3 3
3 Alex 9 6
4 Tim 5 9
5 Lisa 7 3
6 MJ 2 1
[[2]]
x1 x2 x3
1 Alex 3 3
3 Tyler 5 5
4 Ben 7 3
5 Lisa 2 2
6 MJ NA NA
[[3]]
x1 x2 x3
1 Lisa 3 3
3 Tyler 9 6
4 Ben 5 9
5 Lisa 7 3
6 MJ 2 1
CodePudding user response:
library(tidyverse)
df_list %>%
map(., ~ .x %>%
filter(x1 != "ABC"))
[[1]]
x1 x2 x3
1 Ben 3 3
2 Alex 9 6
3 Tim 5 9
4 Lisa 7 3
5 MJ 2 1
[[2]]
x1 x2 x3
1 Alex 3 3
2 Tyler 2 6
3 Ben 5 5
4 Lisa 7 3
5 MJ 2 2
[[3]]
x1 x2 x3
1 Lisa 3 3
2 Tyler 9 6
3 Ben 5 9
4 Lisa 7 3
5 MJ 2 1