我想计算一个变量" value",这取决于" a"和" 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"值= ....
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)
我试过这样:
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))
但它没有用。
所以任何人都可以告诉我如何计算&#34;价值&#34;。
答案 0 :(得分:1)
在评论Sotos和您的澄清之后,您可能需要:
library(dplyr)
df %>%
group_by(type) %>%
mutate(value = ((a-mean(a))/sd(a) +(b-mean(b)/sd(b))/2))