I have a list of data frames like this:
I want to know how can I keep data frames with 15 columns and remove other data frames in this list in R.
I have a list of data frames like this:
I want to know how can I keep data frames with 15 columns and remove other data frames in this list in R.
For your future questions, please avoid screenshots and share an actual object using the dput() function.
You can use purrr::keep():
library(tidyverse)
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.
We may also do this with Filter from base R
Filter(function(x) ncol(x) == 15, out)
Or another option is sapply to get the number of columns and then create a logical vector to subset the list
out[sapply(out, ncol) == 15]
An alternative to ncol is length. length gives the number of columns of a dataframe:
my_list[sapply(my_list, length)==15]