我的数据集“data1”有点像这样
Price class
243 1
32 2
45 3
245 1
67 2
343 3
567 1
.
.
依此类推,在类列 1、2、3 中不断重复,直到数据结束(298 个观测值)。
我想聚合它,这样我就能得到每个类的平均值。数据应该看起来像。数据应该位于新的数据集“classdata”
class column_name
1 mean of all class 1 prices
2 mean of all class 2 prices
3 mean of all class 3 prices
我尝试了这段代码
classdata = aggregate(x=data1$Price, by=list(data1$class), FUN="mean")
但我没有得到想要的结果。请帮忙。
最佳答案
您可能需要正确的列名称。要获取它们,请将 x=
放入列表中,并在两个参数中命名列表。
aggregate(x=list(column_name=data1$Price), by=list(class=data1$class), FUN="mean")
# class column_name
# 1 1 351.6667
# 2 2 49.5000
# 3 3 194.0000
数据:
data1 <- structure(list(Price = c(243L, 32L, 45L, 245L, 67L, 343L, 567L
), class = c(1L, 2L, 3L, 1L, 2L, 3L, 1L)), class = "data.frame", row.names = c(NA,
-7L))
关于r - 如何在r中创建具有按月聚合值的新数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63170296/