Remove dataframes from list of dataframes using loop

Viewed 1510

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?

2 Answers
Related