重新格式化您的问题
您真的应该学会以简单、可重复的方式向您提问。例如,我认为这是对您的问题的等效描述:
set.seed(0) ## set random seed for reproducibility
## some toy data, open access to everyone to play with
## use simply variable name `x`, `y`, `foo`, not those from special context
foo <- data.frame(y = runif(100),
x = sample(letters[1:4], 100, replace = TRUE))
## result from table:
sort(table(foo$x), decreasing = TRUE)
# c b a d
# 33 25 21 21
## your call to aggregation
aggregate(y ~ x, foo, mean)
## the undesired output you see
x y
1 a 0.5537179
2 b 0.5263702
3 c 0.4358863
4 d 0.6145186
这是你想要的输出:
x y
1 c 0.4358863
2 b 0.5263702
3 a 0.5537179
4 d 0.6145186
如果您以上述方式提出问题,人们更容易理解和帮助。这种转变是一项重要的技能。
一种可能的解决方案
你可以试试这个:
## store the result of table() and aggregate()
count <- sort(table(foo$x), decreasing = TRUE)
oo <- aggregate(y ~ x, foo, mean)
## reordering
oo <- oo[match(names(count), oo$x), ]
rownames(oo) <- 1:length(count)
x y
1 c 0.4358863
2 b 0.5263702
3 a 0.5537179
4 d 0.6145186
如果您想将count 附加到oo,请执行以下操作:
oo$count <- as.integer(count)
oo
x y count
1 c 0.4358863 33
2 b 0.5263702 25
3 a 0.5537179 21
4 d 0.6145186 21