按组在 R 中的数据框上运行自定义函数

标签 r function aggregate dplyr

让自定义函数循环遍历数据框中的组时遇到了一些麻烦。

以下是一些示例数据:

set.seed(42)
tm <- as.numeric(c("1", "2", "3", "3", "2", "1", "2", "3", "1", "1"))
d <- as.numeric(sample(0:2, size = 10, replace = TRUE))
t <- as.numeric(sample(0:2, size = 10, replace = TRUE))
h <- as.numeric(sample(0:2, size = 10, replace = TRUE))

df <- as.data.frame(cbind(tm, d, t, h))
df$p <- rowSums(df[2:4])

我创建了一个自定义函数来计算值 w:
calc <- function(x) {
  data <- x
  w <- (1.27*sum(data$d) + 1.62*sum(data$t) + 2.10*sum(data$h)) / sum(data$p)
  w
  }

当我在整个数据集上运行该函数时,我得到以下答案:
calc(df)
[1]1.664474

理想情况下,我想返回按 tm 分组的结果,例如:
tm     w
1    result of calc
2    result of calc
3    result of calc

到目前为止,我已经尝试使用 aggregate使用我的函数,但出现以下错误:
aggregate(df, by = list(tm), FUN = calc)
Error in data$d : $ operator is invalid for atomic vectors

我觉得我已经盯着这个太久了,有一个明显的答案。任何意见,将不胜感激。

最佳答案

你可以试试split :

sapply(split(df, tm), calc)

#       1        2        3 
#1.665882 1.504545 1.838000 

如果你想要一个列表 lapply(split(df, tm), calc) .

或与 data.table :
library(data.table)

setDT(df)[,calc(.SD),tm]
#   tm       V1
#1:  1 1.665882
#2:  2 1.504545
#3:  3 1.838000

关于按组在 R 中的数据框上运行自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31431322/

相关文章:

使用别名的 VHDL 聚合分配

MySQL:聚合临时表中多个对象的更改

r - 如何使用 R 中的 data.table 查找股票的月返回率?

security - 如何防止匿名用户删除/编辑我在 couchDB 中的文档?

r - 条形图中的美学错误(ggplot,R)

c# - 传递一个成员函数,如 C++ 中的 std::function(如 C# 中)

javascript - JavaScript 中的 str.fun()/str.fun/fun(str) 有什么区别?

R:基于因子或数字的聚合

r - 控制 grid.layout 中的内部图形边距

r - 使用两个等长向量为行和列索引索引矩阵