一次聚合多个列
Aggregate multiple columns at once
我有一个这样的数据框:
x <-
id1 id2 val1 val2 val3 val4
1 a x 1 9
2 a x 2 4
3 a y 3 5
4 a y 4 9
5 b x 1 7
6 b y 4 4
7 b x 3 9
8 b y 2 8
我希望通过 id1 和 id2 汇总以上内容。我希望能够同时获取val1,val2,val3,val4的means
我该怎么做?
这是我目前拥有的,但它仅适用于 1 列:
agg <- aggregate(x$val1, list(id11 = x$id1, id2= x$id2), mean)
names(agg)[3] <- c("val1") # Rename the column
此外,我如何重命名在上面给出的相同语句中作为均值输出的列
我们可以使用aggregate
的公式方法。 ~
的 'rhs' 上的变量是分组变量,而 .
代表 'df1' 中的所有其他变量(从示例中,我们假设我们需要 mean
对于除分组之外的所有列),指定数据集和函数 (mean
).
aggregate(.~id1+id2, df1, mean)
或者我们可以在分组后使用 dplyr
中的 summarise_each
(group_by
)
library(dplyr)
df1 %>%
group_by(id1, id2) %>%
summarise_each(funs(mean))
或将 summarise
与 across
一起使用(dplyr
开发版本 - ‘0.8.99.9000’
)
df1 %>%
group_by(id1, id2) %>%
summarise(across(starts_with('val'), mean))
或者另一个选项是 data.table
。我们将 'data.frame' 转换为 'data.table' (setDT(df1)
,按 'id1' 和 'id2' 分组,我们遍历 data.table (.SD
) 并得到 mean
.
library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)]
数据
df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b",
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"),
val1 = c(1L,
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L,
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))
你可以试试:
agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)
我有一个这样的数据框:
x <-
id1 id2 val1 val2 val3 val4
1 a x 1 9
2 a x 2 4
3 a y 3 5
4 a y 4 9
5 b x 1 7
6 b y 4 4
7 b x 3 9
8 b y 2 8
我希望通过 id1 和 id2 汇总以上内容。我希望能够同时获取val1,val2,val3,val4的means
我该怎么做?
这是我目前拥有的,但它仅适用于 1 列:
agg <- aggregate(x$val1, list(id11 = x$id1, id2= x$id2), mean)
names(agg)[3] <- c("val1") # Rename the column
此外,我如何重命名在上面给出的相同语句中作为均值输出的列
我们可以使用aggregate
的公式方法。 ~
的 'rhs' 上的变量是分组变量,而 .
代表 'df1' 中的所有其他变量(从示例中,我们假设我们需要 mean
对于除分组之外的所有列),指定数据集和函数 (mean
).
aggregate(.~id1+id2, df1, mean)
或者我们可以在分组后使用 dplyr
中的 summarise_each
(group_by
)
library(dplyr)
df1 %>%
group_by(id1, id2) %>%
summarise_each(funs(mean))
或将 summarise
与 across
一起使用(dplyr
开发版本 - ‘0.8.99.9000’
)
df1 %>%
group_by(id1, id2) %>%
summarise(across(starts_with('val'), mean))
或者另一个选项是 data.table
。我们将 'data.frame' 转换为 'data.table' (setDT(df1)
,按 'id1' 和 'id2' 分组,我们遍历 data.table (.SD
) 并得到 mean
.
library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)]
数据
df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b",
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"),
val1 = c(1L,
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L,
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))
你可以试试:
agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)