使用[tapply]

时间:2017-07-25 16:47:17

标签: r function tapply

我在显示结果方面遇到了一些问题。基本上我将3个向量存储到数据帧中,并在将新向量与数据帧组合之前执行一些计算并存储到新向量中。

h=c(155,150,165,190,177)
w=c(85,90,72,99,55)
g=c("F","F","M","F","M")
df=data.frame(h,w,g)
row.names(df)=c("alpha","bravo","charlie","foxtrot","echo")
bmi=tapply(df$w,df$h,function(calc){(df$w/(df$h)^2)*10000})
cbind(df,bmi)

打印结果是

        h  w g                                              bmi
alpha   155 85 F 35.37981, 40.00000, 26.44628, 27.42382, 17.55562
bravo   150 90 F 35.37981, 40.00000, 26.44628, 27.42382, 17.55562
charlie 165 72 M 35.37981, 40.00000, 26.44628, 27.42382, 17.55562
foxtrot 190 99 F 35.37981, 40.00000, 26.44628, 27.42382, 17.55562
echo    177 55 M 35.37981, 40.00000, 26.44628, 27.42382, 17.55562

但是,我想要的只是显示

         h  w g  bmi
alpha   155 85 F 35.37981 
bravo   150 90 F 40.00000
charlie 165 72 M 26.44628
foxtrot 190 99 F 27.42382
echo    177 55 M 17.55562

0 个答案:

没有答案