繁体   English   中英

在 R 中使用 tapply(dataframe, index, function) 作为 function 2 列的参数

[英]Use tapply(dataframe , index, function) in R giving as argument to the function 2 columns

我想在 dataframe 上使用 tapply() function,用索引对行进行分组。 我的问题是我将传递给 function 的参数不是单列,而是一对列。 这是因为数据框的 2 列代表 xy 点,它们旨在作为对。 运行 tapply(dataframe, indices, function) 给我的错误是索引的长度与 tapply 不同。 我该如何解决这个问题? 谢谢!

如果要汇总的列不止一列,请使用aggregate而不是tapply (因为tapply适用于单个列)

aggregate(.~ indexes, transform(df1, indexes = indexes), FUN = yourfun)

或者另一种选择by

by(df1, list(indexes), FUN = yourfun)

或者使用tidyverse可能更灵活

library(dplyr)
df1 %>%
    group_by(indexes) %>%
    summarise(across(c(x, y), yourfun), .groups = 'drop')

使用一个小的可重现示例

indexes = rep(1:2, c(3, 2))
by(mtcars[1:5, 1:5], indexes, FUN = sum)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM