R 数据帧中按因子分组运算

R 数据帧中按因子分组运算,r,R,考虑以下数据帧 ## Example data frame z1<-c("a", "b", "c", "c", "b", "a", "a", "b", "c") ##groups z2<-c("x", "x", "x", "y", "y", "y", "z", "z", "z") ##experiments z3<-c(2,4,8,15,9,3,1,2,3) ##results df<-d

考虑以下数据帧

 ## Example data frame
    z1<-c("a", "b", "c", "c", "b", "a", "a", "b", "c") ##groups
    z2<-c("x", "x", "x", "y", "y", "y", "z", "z", "z") ##experiments
    z3<-c(2,4,8,15,9,3,1,2,3)                          ##results
    df<-data.frame(group=z1, id=z2, res=z3)            ##z1, z2, and z3 to data frame
我的想法是,我应该用以下方法来解决这个问题:

###function to check whether group=a, returns TRUE/FALSE
checkA<-function(x){
  if(x=="a"){
    res=TRUE
  }else {
    res=FALSE
  }
return(res)
}

### checks whether a is in df$group
df$check<-lapply(df$group, checkA)
###函数,用于检查group=a是否返回真/假

checkA您可以使用
by
将函数应用于数据子集:

df$z4 <- unlist(by(df, df$id, FUN = function(x) x$res / x$res[x$group == "a"]))

df
  group id res z4
1     a  x   2  1
2     b  x   4  2
3     c  x   8  4
4     c  y  15  5
5     b  y   9  3
6     a  y   3  1
7     a  z   1  1
8     b  z   2  2
9     c  z   3  3
df$z4
df$z4 <- unlist(by(df, df$id, FUN = function(x) x$res / x$res[x$group == "a"]))

df
  group id res z4
1     a  x   2  1
2     b  x   4  2
3     c  x   8  4
4     c  y  15  5
5     b  y   9  3
6     a  y   3  1
7     a  z   1  1
8     b  z   2  2
9     c  z   3  3