R聚合找不到变量

R aggregate can't find variable

我正在尝试使用聚合,但找不到索引变量。

df1 <- iris
agg1 <- aggregate(df1, by = list(Species), FUN = sum, na.rm = T, data = df1)

Error in aggregate.data.frame(df1, by = list(Species), FUN = sum, na.rm = T,  : 
  object 'Species' not found

有什么建议吗?

agg1 <- aggregate(df1[-5], by=list(df1$Species), FUN=sum, na.rm=T)
agg1
#     Group.1 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

不要忘记从聚合中取出非数字列。并用 df1$Specieswith(df1, aggregate(df1[-5], by=list(Species)..) 指定列。当您不使用注释中的公式方法时, data=df1 也是不必要的。

你需要

detach(df)

发布数据列。