Home > database >  remove rows contains a value in all data frames of a list
remove rows contains a value in all data frames of a list

Time:08-01

I have a list (L) which some data frames have a value of -9999. How should I remove all rows in any data frame which contains -9999? the result should be like R list.

L1 = data.frame(A1 = c(1:4) , B1 = c(1,2,-9999,3) , C1 = c(1:4))
L2 = data.frame(A2 = c(1:4) , B2 = c(1:4))
L3 = data.frame(A3 = c(1:4) , B3 = c(1,-9999,2,3))
L=list(L1,L2, L3)
R1 = data.frame(A1 = c(1,2,4) , B1 = c(1,2,3) , C1 = c(1,2,4))
R2 = data.frame(A2 = c(1:4) , B2 = c(1:4))
R3 = data.frame(A3 = c(1,3,4) , B3 = c(1,2,3))
R=list(R1,R2, R3)

CodePudding user response:

library(dplyr)
L %>% purrr::map(~.x  %>% filter(if_all(everything(), ~ .x != -9999)))

Result:

[[1]]
  A1 B1 C1
1  1  1  1
2  2  2  2
3  4  3  4

[[2]]
  A2 B2
1  1  1
2  2  2
3  3  3
4  4  4

[[3]]
  A3 B3
1  1  1
2  3  2
3  4  3

CodePudding user response:

You could use the following code with lapply that remove rows of every dataframe where we can use apply with any that removes every row containing -9999 like this:

L1 = data.frame(A1 = c(1:4) , B1 = c(1,2,-9999,3) , C1 = c(1:4))
L2 = data.frame(A2 = c(1:4) , B2 = c(1:4))
L3 = data.frame(A3 = c(1:4) , B3 = c(1,-9999,2,3))
L=list(L1,L2, L3)
lapply(L, function(x) {x <- x[!apply(x==-9999,1,any),]})
#> [[1]]
#>   A1 B1 C1
#> 1  1  1  1
#> 2  2  2  2
#> 4  4  3  4
#> 
#> [[2]]
#>   A2 B2
#> 1  1  1
#> 2  2  2
#> 3  3  3
#> 4  4  4
#> 
#> [[3]]
#>   A3 B3
#> 1  1  1
#> 3  3  2
#> 4  4  3

Created on 2022-07-31 by the reprex package (v2.0.1)

  • Related