【问题标题】:extract all dataframes of a list wich not containing certain columnname提取不包含特定列名的列表的所有数据帧
【发布时间】:2023-01-20 21:14:44
【问题描述】:

我确实有这样的清单:

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)
Hight <- c(13, 41, 32, 58, 26)
Weight <- c(11,43,23,43,123)

df1 <- data.frame(Name, Age, Hight, Weight)
df2 <- data.frame(Name, Age, Hight)
df3<- data.frame(Name, Age, Weight)

list(df1, df2, df3)

我现在想提取所有不包含 Hight 或 Weight 列的数据帧(或数据帧的名称)。

所以我在这种情况下的预期输出是list(df1)

【问题讨论】:

    标签: r list dataframe


    【解决方案1】:

    一种可能的方法是使用 for 循环:

    dfs <- list(df1, df2, df3)
    
    n <- length(dfs)
    index <- NULL # index of dataframes to be used
    for (i in 1:n){
      if ("Hight" %in% names(dfs[[i]]) & "Weight" %in%  names(dfs[[i]]))
        index <- c(index, i)
    }
    
    dfs[index]
    

    【讨论】:

      【解决方案2】:
      df_list <- list(df1, df2, df3)
      have_all_columns <- purrr:::map_lgl(df_list, ~all(c( "Hight", "Weight") %in% names(.x)))
      df_list[have_all_columns]
      

      【讨论】:

        【解决方案3】:

        你可以用这个

        l <- list(df1, df2, df3)
        
        l[sapply(l , (x) all(c('Weight', 'Hight') %in% colnames(x)))]
        
        • 输出
        [[1]]
           Name Age Hight Weight
        1   Jon  23    13     11
        2  Bill  41    41     43
        3 Maria  32    32     23
        4   Ben  58    58     43
        5  Tina  26    26    123
        

        【讨论】:

        • 您可以使用 sapply 跳过 unlist 步骤
        猜你喜欢
        • 1970-01-01
        • 2020-05-28
        • 2015-05-02
        • 1970-01-01
        • 1970-01-01
        • 2022-12-31
        • 2017-06-15
        • 2013-08-11
        • 1970-01-01
        相关资源
        最近更新 更多