Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove dataframes from list of dataframes using loop

I want to remove parts from a list to reduce the list to the elements of it that have a certain number of columns.

This a dummy example of what I'm trying to do:

    #1: define the list
    tables = list(mtcars,iris)

    for(k in 1:length(tables)) {
      # 2: be sure that each element is shaped as dataframe and not matrix
      tables[[k]] = as.data.frame(tables[[k]])
      # 3: remove elements that have more or less than 5 columns
      if(ncol(tables[[k]]) != 5) {
        tables <- tables[-k]
      }
    }

another option I tried:

    #1: define the list
    tables = list(mtcars,iris)

    for(k in 1:length(tables)) {
      # 2: be sure that each element is shaped as dataframe
      tables[[k]] = as.data.frame(tables[[k]])
      # 3: remove elements that have more or less than 5 columns
      if(ncol(tables[[k]]) != 5) {
        tables[[-k]] <- NULL
      }
    }

I'm getting

Error in tables[[k]] : subscript out of bounds.

Is there an alternative and correct approach?

like image 895
pachadotdev Avatar asked Jul 14 '26 22:07

pachadotdev


1 Answers

We can use Filter

Filter(function(x) ncol(x)==5, tables)

Or with sapply to create a logical index and subset the list

tables[sapply(tables, ncol)==5]

Or as @Sotos commented

tables[lengths(tables)==5]

lengths return the length of each list element convert it a logical vector and subset the list. The length of a data.frame is the number of columns it has

like image 154
akrun Avatar answered Jul 17 '26 16:07

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!