2

我有一个数据表,我想在其中标准化“性别”中的名称并根据每个组计算几何平均值(如表中的 x、y 和 z)。

感谢您的帮助。下面是data.table。

library(data.table)
dt <- data.table(Group = c("x","x","x","y","z","z"), Sex = c("Man","Female","Feminine","Male","M","F"), Score = c(0,0.4,0.1,0.5,3,2.1))

谢谢你。

4

1 回答 1

1

这是你想要的吗?

geomean <- function(v) prod(v)**(1/length(v))
res <- tapply(dt$Score, dt$Group, geomean)

这使

> res
      x       y       z 
0.00000 0.50000 2.50998 

或用于ave创建新列

dt <- within(dt,gm <- ave(Score,Group,FUN = geomean))
> dt
Group      Sex Score      gm
1:     x      Man   0.0 0.00000
2:     x   Female   0.4 0.00000
3:     x Feminine   0.1 0.00000
4:     y     Male   0.5 0.50000
5:     z        M   3.0 2.50998
6:     z        F   2.1 2.50998

编辑

如果您想同时按Groupand对数据进行分组,请Sex尝试以下操作

dt <- within(transform(dt,Sex = toupper(substr(Sex,1,1))),
             gm <- ave(Score,Group,Sex,FUN = geomean))

因此

> dt
   Group Sex Score  gm
1:     x   M   0.0 0.0
2:     x   F   0.4 0.2
3:     x   F   0.1 0.2
4:     y   M   0.5 0.5
5:     z   M   3.0 3.0
6:     z   F   2.1 2.1
于 2020-04-20T08:41:59.200 回答