pauke Huang
pauke Huang

Reputation: 111

Calculate a variable depending on another variables by row

I want to calculate a variable "value", which is depending on "a" and "b":

type "A" value = (sum(a_A1) - mean(a_A))/sd(a_A) + (sum(b_A1) - mean(b_A))/sd(b_A))/2

type "B" value = (sum(a_B1) - mean(a_B))/sd(a_B) + (sum(b_B1) - mean(b_B))/sd(b_B))/2

type "C" value = ....

set.seed(101)

type <- c("A","B","A","A","C","B", "C", "World")
a <- abs(rnorm(8) * 5)
b <- abs(rnorm(8) * 5)
df <- data.frame(type,a,b)

I have try like this:

df <- transform(df, value = ave(df$a, df$b, df$type, 
                    FUN = function(a,b) ((sum(a)-mean(a))/sd(a) +(sum(b)-mean(b)/sd(b))/2))

but it doesn't work.

So any one can tell how I calculate "value".

Upvotes: 1

Views: 107

Answers (1)

tuRmerix
tuRmerix

Reputation: 41

After the comments Sotos and your clarification, you might need:

library(dplyr)

df %>% 
 group_by(type) %>% 
 mutate(value = ((a-mean(a))/sd(a) +(b-mean(b)/sd(b))/2))

Upvotes: 1

Related Questions