5xum
5xum

Reputation: 5535

R aggregate function with two values

Let's say I have a function that takes two vectors:

someFunction <- function(x,y){
  return(mean(x+y));
}

And say I have some data

toy <- data.frame(a=c(1,1,1,1,1,2,2,2,2,2), b=rnorm(10), c=rnorm(10))

What I want to do is return the result of the function someFunction for each value of toy$a, i.e. I want to acchieve the same result as the code

toy$d <- toy$b + toy$c
result <- aggregate(toy$d, list(toy$a), mean)

However, in real life, the function someFunction is way more complicated and it needs two inputs, so the workaround in this toy example is not possible. So, what I want to do is:

Upvotes: 1

Views: 515

Answers (2)

Sotos
Sotos

Reputation: 51592

library(data.table)
toy <- data.table(toy)
toy[, list(New_col = someFunction(b, c)), by = 'a']

Upvotes: 2

Kota Mori
Kota Mori

Reputation: 6740

Checkout dplyr package, specifically group_by and summarize functions. Assuming that you want to compute someFunction(b, c) for each value of a, the syntax would look like

library(dplyr)
data %>% group_by(a) %>% summarize(someFunction(b, c))

Upvotes: 2

Related Questions