Home > database >  Filter a list based on number of columns of tables in R
Filter a list based on number of columns of tables in R

Time:10-04

I have a list of data frames like this: enter image description here I want to know how can I keep data frames with 15 columns and remove other data frames in this list in R.

CodePudding user response:

For your future questions, please avoid screenshots and share an actual object using the dput() function.

You can use purrr::keep():

library(tidyverse)
#> Warning: le package 'tibble' a été compilé avec la version R 4.1.1
f=function(n) matrix(nrow=2, ncol=n) %>% as.data.frame()
x=list(
   df1=f(15),
   df2=f(15),
   df3=f(6),
   df4=f(6),
   df5=f(15)
)
x %>% keep(~ncol(.x)==15)
#> $df1
#>   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15
#> 1 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA
#> 2 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA
#> 
#> $df2
#>   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15
#> 1 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA
#> 2 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA
#> 
#> $df5
#>   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15
#> 1 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA
#> 2 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA

Created on 2021-10-03 by the reprex package (v2.0.0)

The second argument of purrr::keep() (first when piping) is a predicate function that should return a single logical value depending on whether the column should be kept or not.

  • Related