【问题标题】:In R, how do I recursively store columns of a data frame as a data frame?在 R 中,如何将数据框的列递归存储为数据框?
【发布时间】:2021-06-02 16:50:27
【问题描述】:

在 R 中,我想递归地遍历数据框的列并选择每一列以针对给定列制作箱线图。 这是我的尝试

#define dataframe
library(ggplot2)
df <- mpg

#get unique column names
IDs <- unique( colnames(df) )
for (name in IDs){ 
  #goal: store column as a data frame, actual: store column as a list 
  temp <- df[name]
  #plot column of data vs cty miles per gallon
  boxplot(temp ~ df$cty)
}

我收到此错误(因为它需要是数据框而不是列表):

统计错误::model.frame.default(formula = temp ~ df$cty) :
变量“temp”的类型(列表)无效

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    在您初始化df 之后,让我们尝试按照您的方式提取cyl 列:

    library(ggplot2)
    df <- mpg
    str(df["cyl"])
    

    从结果中您可以看到,这提取了一个只有一行的小标题。它没有将一行提取为向量。 boxplot 期望 temp 是一个向量。这解释了错误消息。 tibble 是 data.frame,而 data.frame 不是向量。

    可以这样提取向量:

    > str(df[,"cyl", drop = TRUE])
     int [1:234] 4 4 4 4 6 6 6 4 4 4 ...
    

    或者像这样:

    > str(df[["cyl"]])
     int [1:234] 4 4 4 4 6 6 6 4 4 4 ...
    

    所以我们可以在两个地方修改你的代码

    library(ggplot2)
    df <- mpg[,c(3,4,5,8,9)] # only numeric columns
    
    IDs <- unique( colnames(df) )
    for (name in IDs){ 
      temp <- df[, name, drop = TRUE] # using the drop argument
      boxplot(temp ~ df$cty)
    }
    

    【讨论】:

      【解决方案2】:

      如果我们对数字列执行此操作,请通过检查列是否为 numeric 来获取数字列的 names。然后使用OP的代码。在这里,我们通过指定response 和独立列来创建带有reformulate 的公式,并将boxplot 存储在list 中

      IDs <- setdiff(names(which(sapply(df, is.numeric))), 'cty')
      lst <- vector('list', length(IDs))
      names(lst) <- IDs
      for(name in IDs) {
          lst[[name]] <- boxplot(reformulate('cty', response = name), df)
      }
      

      【讨论】:

        猜你喜欢
        • 2019-09-28
        • 1970-01-01
        • 1970-01-01
        • 2018-10-31
        • 2015-09-22
        • 2020-04-03
        • 2020-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多