gpt4 book ai didi

按列狂欢

转载 作者:行者123 更新时间:2023-12-04 22:46:56 26 4
gpt4 key购买 nike

我想使用 ave在数据框上的许多列(十)上运行:

ave(df[,the_cols], df[,c('site', 'month')], FUN = mean)

问题是 ave运行 mean全部功能 the_cols列在一起。有什么方法可以为每个 the_cols 运行它吗?分别列?

我试着看看其他功能。 tapplyaggregate不同,它们每组只返回一行。我需要 ave行为,即返回与原始 df 中给定的行数相同的行数.还有一个 by函数,但是使用它会非常笨拙,因为它返回一个复杂的列表结构,必须以某种方式进行转换。

当然存在许多笨拙和丑陋(通过 &do.call、多个 *apply 函数调用等)的解决方案,但有一些真正简单和优雅的解决方案吗?

最佳答案

也许我遗漏了一些东西,但是 apply()这里的方法效果很好,不会丑陋或需要任何丑陋的黑客。一些虚拟数据:

df <- data.frame(A = rnorm(20), B = rnorm(20), site = gl(5,4), month = gl(10, 2))

出什么问题了:
sapply(df[, c("A","B")], ave, df$site, df$month)

?通过 data.frame() 将其强制为数据框如果你真的想要那个。
R> sapply(df[, c("A","B")], ave, df$site, df$month)
A B
[1,] 0.0775 0.04845
[2,] 0.0775 0.04845
[3,] -1.5563 0.43443
[4,] -1.5563 0.43443
[5,] 0.7193 0.01151
[6,] 0.7193 0.01151
[7,] -0.9243 -0.28483
[8,] -0.9243 -0.28483
[9,] 0.3316 0.14473
[10,] 0.3316 0.14473
[11,] -0.2539 0.20384
[12,] -0.2539 0.20384
[13,] 0.5558 -0.37239
[14,] 0.5558 -0.37239
[15,] 0.1976 -0.22693
[16,] 0.1976 -0.22693
[17,] 0.2031 1.11041
[18,] 0.2031 1.11041
[19,] 0.3229 -0.53818
[20,] 0.3229 -0.53818

再凑合一下,怎么样
AVE <- function(df, cols, ...) {
dots <- list(...)
out <- sapply(df[, cols], ave, ...)
out <- data.frame(as.data.frame(dots), out)
names(out) <- c(paste0("Fac", seq_along(dots)), cols)
out
}

R> AVE(df, c("A","B"), df$site, df$month)
Fac1 Fac2 A B
1 1 1 0.0775 0.04845
2 1 1 0.0775 0.04845
3 1 2 -1.5563 0.43443
4 1 2 -1.5563 0.43443
5 2 3 0.7193 0.01151
6 2 3 0.7193 0.01151
7 2 4 -0.9243 -0.28483
8 2 4 -0.9243 -0.28483
9 3 5 0.3316 0.14473
10 3 5 0.3316 0.14473
11 3 6 -0.2539 0.20384
12 3 6 -0.2539 0.20384
13 4 7 0.5558 -0.37239
14 4 7 0.5558 -0.37239
15 4 8 0.1976 -0.22693
16 4 8 0.1976 -0.22693
17 5 9 0.2031 1.11041
18 5 9 0.2031 1.11041
19 5 10 0.3229 -0.53818
20 5 10 0.3229 -0.53818

使用 ... 的详细信息暂时避开我,但您应该能够为 Fac1 获得更好的名称等我在这里使用。

我将为您提供另一种表示形式: aggregate()但使用 ave()函数而不是 mean() :
R> aggregate(cbind(A, B) ~ site + month, data = df, ave)
site month A.1 A.2 B.1 B.2
1 1 1 0.0775 0.0775 0.04845 0.04845
2 1 2 -1.5563 -1.5563 0.43443 0.43443
3 2 3 0.7193 0.7193 0.01151 0.01151
4 2 4 -0.9243 -0.9243 -0.28483 -0.28483
5 3 5 0.3316 0.3316 0.14473 0.14473
6 3 6 -0.2539 -0.2539 0.20384 0.20384
7 4 7 0.5558 0.5558 -0.37239 -0.37239
8 4 8 0.1976 0.1976 -0.22693 -0.22693
9 5 9 0.2031 0.2031 1.11041 1.11041
10 5 10 0.3229 0.3229 -0.53818 -0.53818

请注意声明的输出,但如果需要,它很容易 reshape 。

关于按列狂欢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21340431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com