2017-05-27 119 views
2

我想从列表中删除部分以将列表减少为具有特定列数的列表中的元素。使用循环从数据帧列表中删除数据帧

的什么,我试图做一个虚拟的例子:

#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] 
     } 
    } 

另一种选择我想:

#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 
     } 
    } 

我越来越

错误表[ [k]]:下标越界。

有没有其他正确的方法?

回答

2

我们可以使用Filter

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

或用sapply创建一个逻辑索引和子集list

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

或者作为@Sotos评论

tables[lengths(tables)==5] 

lengths返回length每个list元素将其转换为逻辑向量和子集list。一个data.framelength是列数有

+0

将修剪到最大。 5列的数量,我想从列表中删除列数不同于5的列中的元素 ,但我会尝试lapply – pachamaltese

+1

@pachamaltese更新后 – akrun

+2

也'长度(表格) – Sotos

1

对于您可以使用purrr:keep此一tidyverse选项。你只需定义一个谓词函数,如果它是true,它将保留list元素,如果为false,则将其移除。在这里我已经用公式选项完成了。


library(purrr) 

tables <- list(mtcars, iris) 

result <- purrr::keep(tables, ~ ncol(.x) == 5) 

str(result) 

#> List of 1 
#> $ :'data.frame': 150 obs. of 5 variables: 
#> ..$ Sepal.Length: num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... 
#> ..$ Sepal.Width : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... 
#> ..$ Petal.Length: num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... 
#> ..$ Petal.Width : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... 
#> ..$ Species  : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...