【问题标题】:Aggregate function not working with paste0 in R聚合函数不适用于 R 中的 paste0
【发布时间】:2023-03-09 01:57:02
【问题描述】:

我有一个包含子区数据的数据框 subdist.df。我正在尝试根据数据框中的公共属性(即DISTRICT 列)总结行的值。

以下代码行

hello2 <-aggregate(.~DISTRICT, subdist.df,sum)

但是这个没有。

hello <-aggregate(noquote(paste0(".~","DISTRICT")), subdist.df,sum)

我无法理解为什么会这样。我需要在一个函数中使用它,其中DISTRICT 可以是用户的任何输入作为参数。

【问题讨论】:

  • 请展示一个可重现的小例子和预期的输出
  • 我会建议对data.frame使用S3方法,而不是聚合的公式接口。虹膜示例:var &lt;- "Species"; aggregate(iris[setdiff(names(iris), var)], by = list(iris[[var]]), sum)

标签: r dataframe aggregate-functions


【解决方案1】:

以 iris data.frame 为例:

aggregate(.~Species, iris, sum)
     Species Sepal.Length Sepal.Width Petal.Length Petal.Width
1     setosa        250.3       171.4         73.1        12.3
2 versicolor        296.8       138.5        213.0        66.3
3  virginica        329.4       148.7        277.6       101.3

下面的paste0 不起作用,因为noquote 只生成表达式而不是aggregate 函数要求的公式:

aggregate(noquote(paste0(".~","Species")), iris, sum)
Error in aggregate.data.frame(as.data.frame(x), ...) : 
  arguments must have same length

相反,在paste0 之前添加as.formula 会起作用:

aggregate(as.formula(paste0(".~","Species")), iris, sum)

     Species Sepal.Length Sepal.Width Petal.Length Petal.Width
1     setosa        250.3       171.4         73.1        12.3
2 versicolor        296.8       138.5        213.0        66.3
3  virginica        329.4       148.7        277.6       101.3

【讨论】:

    猜你喜欢
    • 2018-02-22
    • 2019-04-06
    • 2021-12-31
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多