簡體   English   中英

如何計算r中的比例?

[英]How to calculate the proportion in r?

我有一個數據框,我想計算比例。 該表如下所示:

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

我想知道接種疫苗的所有地區所占的比例。 我認為我需要將合格的色譜柱和免疫的色譜柱加在一起,然后使用免疫的色譜柱除以合格的色譜柱。 但是我不太確定如何編寫代碼。 如果有人可以幫助,那就太好了。 謝謝!!

我不確定您想要什么,但很可能是其中一個在末尾的注釋中可重復定義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)

只需將兩列分開:

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

我猜想OP就是這樣的:

數據(data.frame 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

這是非常基本的,但這似乎是個問題。

由於您希望“ Immunised列的總和與“ Eligible比率,您可以這樣做

sum(df$Immunised)/sum(df$Eligible)
#[1] 0.770869

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM