[英]In an R data frame, for a given row, how can I find what percentage a value in column A is of a value in column B?
Say I have a data frame as follows:假设我有一个数据框,如下所示:
dataDF <- data.frame(
cola = c(10, 15, 30),
colb = c(100, 300, 800)
)
cola colb
1 10 100
2 15 300
3 30 800
How can I find what percent column a row 1 (10) is of column b row 1 (100), and so on for rows 2 and 3?如何找到第 1 (10) 行是第 b 行第 1 (100) 行的百分比列,依此类推第 2 行和第 3 行?
Thanks.谢谢。
One option is prop.table
and specify the margin
.一种选择是prop.table
并指定margin
。 Here it is by row, so we use 1
and if it is column, it would be 2这里是按行,所以我们用1
,如果是列,那就是2
prop.table(as.matrix(dataDF), 1)
Another way which is useful if you want to have a column containing the percentages is this:如果您想要包含百分比的列,另一种有用的方法是:
library(dplyr)
dataDF <- data.frame(
cola = c(10, 15, 30),
colb = c(100, 300, 800)
)
dataDF2 <- mutate(dataDF, colc = cola/colb*100)
dataDF2
cola colb colc
1 10 100 10.00
2 15 300 5.00
3 30 800 3.75
Another solution with data.table package
:另一个带有data.table package
解决方案:
library(data.table)
setDT(dataDF)[, colc := cola/colb*100]
> dataDT
cola colb colc
1: 10 100 10.00
2: 15 300 5.00
3: 30 800 3.75
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.