gpt4 book ai didi

r - 使用列表中数据帧的加权平均值创建新数据帧

转载 作者:行者123 更新时间:2023-12-01 12:39:44 24 4
gpt4 key购买 nike

我有很多数据框存储在一个列表中,我想从这些数据中创建加权平均值并将结果存储在一个新的数据框中。例如,列表:

dfs <- structure(list(df1 = structure(list(A = 4:5, B = c(8L, 4L), Weight = c(TRUE, TRUE), Site = c("X", "X")), 
.Names = c("A", "B", "Weight", "Site"), row.names = c(NA, -2L), class = "data.frame"),
df2 = structure(list(A = c(6L, 8L), B = c(9L, 4L), Weight = c(FALSE, TRUE), Site = c("Y", "Y")),
.Names = c("A", "B", "Weight", "Site"), row.names = c(NA, -2L), class = "data.frame")),
.Names = c("df1", "df2"))

在此示例中,我想使用列 ABWeight 作为加权平均值。我还想把Site等相关数据移过来,想把TRUEFALSE的个数相加。我想要的结果看起来像:

result <- structure(list(Site = structure(1:2, .Label = c("X", "Y"), class = "factor"), 
A.Weight = c(4.5, 8), B.Weight = c(6L, 4L), Sum.Weight = c(2L,
1L)), .Names = c("Site", "A.Weight", "B.Weight", "Sum.Weight"
), class = "data.frame", row.names = c(NA, -2L))


Site A.Weight B.Weight Sum.Weight
1 X 4.5 6 2
2 Y 8.0 4 1

上面只是一个非常简单的例子,但是我的真实数据在列表中有很多数据框,而且列比我想要的 AB 更多计算加权平均值。我还有几个类似于 Site 的列,它们在每个数据框中都是常量,我想移动到结果。

我可以使用类似的方法手动计算加权平均值

weighted.mean(dfs$df1$A, dfs$df1$Weight)
weighted.mean(dfs$df1$B, dfs$df1$Weight)
weighted.mean(dfs$df2$A, dfs$df2$Weight)
weighted.mean(dfs$df2$B, dfs$df2$Weight)

但我不确定如何以更短、更少“手动”的方式完成此操作。有人有什么建议吗?我最近学习了如何lapply 列表中的数据帧,但到目前为止我的尝试还不是很好。

最佳答案

诀窍是创建一个适用于单个 data.frame 的函数,然后使用 lapply 遍历您的列表。由于 lapply 返回一个列表,我们将使用 do.call 将结果对象rbind 在一起:

foo <- function(data, meanCols = LETTERS[1:2], weightCol = "Weight", otherCols = "Site") {
means <- t(sapply(data[, meanCols], weighted.mean, w = data[, weightCol]))
sumWeight <- sum(data[, weightCol])
others <- data[1, otherCols, drop = FALSE] #You said all the other data was constant, so we can just grab first row
out <- data.frame(others, means, sumWeight)
return(out)
}

在行动中:

do.call(rbind, lapply(dfs, foo))
---
Site A B sumWeight
df1 X 4.5 6 2
df2 Y 8.0 4 1

既然你说这是一个最小的例子,下面是将其扩展到其他列的一种方法。我们将使用 grepl() 并使用正则表达式来识别正确的列。或者,您可以将它们全部写在一个向量中。像这样:

do.call(rbind, lapply(dfs, foo, 
meanCols = grepl("A|B", names(dfs[[1]])),
otherCols = grepl("Site", names(dfs[[1]]))
))

关于r - 使用列表中数据帧的加权平均值创建新数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26111656/

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