[英]Use tapply(dataframe , index, function) in R giving as argument to the function 2 columns
I would like to use the tapply() function on a dataframe, grouping the rows with the indexing.我想在 dataframe 上使用 tapply() function,用索引对行进行分组。 My problem is that the argument I would pass to the function is not a single column, but a pair of columns.我的问题是我将传递给 function 的参数不是单列,而是一对列。 This beacause the 2 columns of the data frame represent xy points, which are intended as couples.这是因为数据框的 2 列代表 xy 点,它们旨在作为对。 Running tapply(dataframe, indexes, function) gives me the error that indexes has length different from tapply.运行 tapply(dataframe, indices, function) 给我的错误是索引的长度与 tapply 不同。 How can I solve this?我该如何解决这个问题? Thank you!谢谢!
If there are more than one column to be summarised, use aggregate
instead of tapply
(as tapply
works for a single column)如果要汇总的列不止一列,请使用aggregate
而不是tapply
(因为tapply
适用于单个列)
aggregate(.~ indexes, transform(df1, indexes = indexes), FUN = yourfun)
Or another option is by
或者另一种选择by
by(df1, list(indexes), FUN = yourfun)
Or it may be more flexible with tidyverse
或者使用tidyverse
可能更灵活
library(dplyr)
df1 %>%
group_by(indexes) %>%
summarise(across(c(x, y), yourfun), .groups = 'drop')
Using a small reproducible example使用一个小的可重现示例
indexes = rep(1:2, c(3, 2))
by(mtcars[1:5, 1:5], indexes, FUN = sum)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.