如何计算r中的比例?

时间:2019-05-11 12:23:07

标签: r

我有一个数据框,我想计算比例。桌子看起来像这样:

                Eligible        Immunised
 Auckland          1778            1426
 Bay of plenty     1194            802
 Canterbury        3461            2731

我想知道所有地区接受免疫接种的比例。我认为我需要将合格的色谱柱和免疫的色谱柱加在一起,然后使用免疫的色谱柱除以合格的色谱柱。但是我不太确定如何编写代码。如果有人可以帮助,那就太好了。谢谢!

4 个答案:

答案 0 :(得分:1)

我不确定您想要什么,但很可能其中之一m在末尾的注释中可重复地定义:

prop.table(m)
prop.table(m, 1)
prop.table(m, 2)
prop.table(colSums(m))
prop.table(rowSums(m))

注意

下次,请以可重复的形式提供您的输入。这次我为您做了:

Lines <- "Eligible        Immunised
Auckland           1778            1426
Bay of plenty      1194            802
Canterbury         3461            2731"
L <- readLines(textConnection(Lines))
DF <- read.csv(text = gsub(" {5,}", ",", L), as.is = TRUE, strip.white = TRUE)
m <- as.matrix(DF)

答案 1 :(得分:1)

只需将两列分开:

df$Proportion <- df$Immunised / df$Eligible

df
                Eligible        Immunised         Proportion
 Auckland          1778            1426            0.8020247
 Bay of plenty     1194            802             0.6716918
 Canterbury        3461            2731            0.7890783

答案 2 :(得分:0)

我想OP想要的就是这样:

数据(数据框架x):

dput( x )
structure(list(Region = c("Auckland", "Bay of plenty", "Canterbury"
), Eligible = c(1778L, 1194L, 3461L), Immunised = c(1426L, 802L, 
2731L)), .Names = c("Region", "Eligible", "Immunised"), 
class = "data.frame", row.names = c(NA, -3L))

proportion部分只是一个新列,其中“免疫接种”占“合格”的百分比:

x$proportion = x$Immunised / x$Eligible
> x
         Region Eligible Immunised proportion
1      Auckland     1778      1426  0.8020247
2 Bay of plenty     1194       802  0.6716918
3    Canterbury     3461      2731  0.7890783

那是非常的基本知识,但这似乎是个问题。

答案 3 :(得分:0)

由于您希望Immunised列与Eligible的总和之比

sum(df$Immunised)/sum(df$Eligible)
#[1] 0.770869
相关问题