我正在寻找一种方法来平均某一列中的常用名称,并基于这种相似性,将其余值平均到一个常用行中。我研究了聚合,但我想我错过了如何在大型数据集中做到这一点,因为它没有按照我希望的方式工作。
假设我有DF1
ID | 位置 | 值2值3 | 值4 | ||
---|---|---|---|---|---|
第一个 | 2 | 4 | 3 | ||
第二次 | |||||
第二次 | 2 | 4 | 5 | 6 | |
第三 | 6 | 1 | 8 | ||
第三次 | 4 | 7 | 5 | 4||
第四个 | 1 | 45 | <1>
您可以使用aggregate
进行尝试
aggregate(df[-1], list(df$ID), mean)
Group.1 Location Value2 Value3 Value4
1 First 2.0 4 3.0 3
2 Fourth 1.0 4 5.0 1
3 Second 1.5 3 5.0 4
4 Third 5.0 4 6.5 6
带dplyr
library(dplyr)
df %>%
group_by(ID) %>%
summarise(across(starts_with(c("Lo","Val")),mean))
# A tibble: 4 × 5
ID Location Value2 Value3 Value4
<chr> <dbl> <dbl> <dbl> <dbl>
1 First 2 4 3 3
2 Fourth 1 4 5 1
3 Second 1.5 3 5 4
4 Third 5 4 6.5 6
数据
df <- structure(list(ID = c("First", "Second", "Second", "Third", "Third",
"Fourth"), Location = c(2L, 1L, 2L, 6L, 4L, 1L), Value2 = c(4L,
2L, 4L, 1L, 7L, 4L), Value3 = c(3L, 5L, 5L, 8L, 5L, 5L), Value4 = c(3L,
2L, 6L, 8L, 4L, 1L)), class = "data.frame", row.names = c(NA,
-6L))