【问题标题】:Filtering out the data frame whose row dimension is zero in R过滤掉R中行维度为零的数据框
【发布时间】:2016-12-08 09:30:12
【问题描述】:

我有许多数据框,例如 df1,df2,...,df11,其尺寸为 20,3; 40,4,; 0,5;...0,2;这些维度在我计算数据帧的程序中并不会保持不变。所以我想过滤掉那些行维度为零的数据帧,例如 dim(df3) 给出 0,5 这是我尝试过的

while(!dim(df(i))[1]==0)
 {

  DF=paste("df",c(1:11))

 }

谢谢

【问题讨论】:

  • 您想要非空数据框的名称还是想要将数据框本身作为一个列表?
  • @joel.wilson,想要数据帧本身

标签: r filter while-loop dimensions


【解决方案1】:

将数据集保存在list中后,我们可以使用Filter

Filter(function(x) nrow(x)>1, mget(paste0("df", 1:11)))

或者另一个选项是sapply 创建一个逻辑向量,然后将list 子集化

lst <- mget(paste0("df", 1:11))
i1 <- sapply(lst, nrow)>0 
lst[i1]

【讨论】:

    【解决方案2】:

    这只是为了解释您可能出错的地方。您应该首选for 而不是while

    如果您只想要非空 data.frames 的名称:

    total_num_dataframes = 4
    DF  =character(0)
    for (i in 1:total_num_dataframes){
      if (dim(get(paste0("df",i)))[1] != 0) 
        DF = c(DF,paste0("df",i))
    
    }
    

    如果你想要 data.frames 本身:

    DF = vector('list', length = total_num_dataframes)
    j = 1
    for (i in 1:total_num_dataframes){
      if (dim(get(paste0("df",i)))[1] != 0) {
        DF[[j]] = get(paste0("df",i))
        j = j+1
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多