R函数中是否有一种方法以该行的单元格值作为参数遍历每行?

问题描述 投票:0回答:1

我想使用同一行的值计算行元素的百分比

我的数据框看起来像这样

     Group.1   a      b    c        d      e   total
1     test1  470.0 5696.0 393.5    0.5    8.0 6568.0
2     test2  646.0 5376.0 279.0    0.5    9.5 6311.0
3     test3  855.0 5279.5 297.0    0.5   11.0 6443.0
4     test4  660.5 7472.0 201.0   11.5  481.5 8826.5
5     test5   87.0 3900.0 119.0   11.5  491.5 4609.0

现在我想计算a,b,c,d和e的百分比

percentage <- t(apply(mydata[-c(1,7)], 1, FUN = function(x) x / Here im not sure how to access the right cell ))

这是否可以使用Apply或是否有更好的方法来实现?

r
1个回答
0
投票

如果我们要向量化

  mydata[-c(1, 7)]/mydata$total

如果我们正在检查元素的总和以计算百分比

 rowSums(mydata[-c(1, 7)])/mydata$total
© www.soinside.com 2019 - 2024. All rights reserved.