簡體   English   中英

如何在R中生成具有累積頻率和相對頻率的頻率表

[英]How to generate a frequency table in R with with cumulative frequency and relative frequency

我是R.的新手。我需要生成一個具有累積頻率和相對頻率的簡單頻率表(如書中)。

所以我想從一些簡單的數據生成

> x
[1] 17 17 17 17 17 17 17 17 16 16 16 16 16 18 18 18 10 12 17 17 17 17 17 17 17 17 16 16 16 16 16 18 18 18 10
[36] 12 15 19 20 22 20 19 19 19

像這樣的表:

            frequency  cumulative   relative
(9.99,11.7]    2            2       0.04545455
(11.7,13.4]    2            4       0.04545455
(13.4,15.1]    1            5       0.02272727
(15.1,16.9]   10           15       0.22727273
(16.9,18.6]   22           37       0.50000000
(18.6,20.3]    6           43       0.13636364
(20.3,22]      1           44       0.02272727

我知道它應該很簡單,但我不知道如何。

我使用此代碼獲得了一些結果:

factorx <- factor(cut(x, breaks=nclass.Sturges(x)))
as.matrix(table(factorx))

你很親密! 有一些函數可以讓你輕松,即cumsum()prop.table() 這就是我可能把它放在一起的方式。 我做了一些隨機數據,但重點是:

#Fake data
x <- sample(10:20, 44, TRUE)
#Your code
factorx <- factor(cut(x, breaks=nclass.Sturges(x)))
#Tabulate and turn into data.frame
xout <- as.data.frame(table(factorx))
#Add cumFreq and proportions
xout <- transform(xout, cumFreq = cumsum(Freq), relative = prop.table(Freq))
#-----
      factorx Freq cumFreq   relative
1 (9.99,11.4]   11      11 0.25000000
2 (11.4,12.9]    3      14 0.06818182
3 (12.9,14.3]   11      25 0.25000000
4 (14.3,15.7]    2      27 0.04545455
5 (15.7,17.1]    6      33 0.13636364
6 (17.1,18.6]    3      36 0.06818182
7   (18.6,20]    8      44 0.18181818

基本函數tablecumsumprop.table應該可以幫到你:

 cbind( Freq=table(x), Cumul=cumsum(table(x)), relative=prop.table(table(x)))
   Freq Cumul   relative
10    2     2 0.04545455
12    2     4 0.04545455
15    1     5 0.02272727
16   10    15 0.22727273
17   16    31 0.36363636
18    6    37 0.13636364
19    4    41 0.09090909
20    2    43 0.04545455
22    1    44 0.02272727

有了cbind並根據自己的喜好命名列,這對你來說應該很容易。 表函數的輸出是一個矩陣,因此該結果也是一個矩陣。 如果這是在一個大的東西上完成,那么這將是更有效的:

tbl <- table(x)
cbind( Freq=tbl, Cumul=cumsum(tbl), relative=prop.table(tbl))

如果您正在尋找預打包的東西,請考慮descr包中的freq()函數。

library(descr)
x = c(sample(10:20, 44, TRUE))
freq(x, plot = FALSE)

或者要獲得累積百分比,請使用ordered()函數

freq(ordered(x), plot = FALSE)

要添加“累積頻率”列:

tab = as.data.frame(freq(ordered(x), plot = FALSE))
CumFreq = cumsum(tab[-dim(tab)[1],]$Frequency)
tab$CumFreq = c(CumFreq, NA)
tab

如果您的數據缺少值,則會向表中添加有效的百分比列。

x = c(sample(10:20, 44, TRUE), NA, NA)
freq(ordered(x), plot = FALSE)

另一種可能性:

 library(SciencesPo)
    x = c(sample(10:20, 50, TRUE))
    freq(x)

我的建議是檢查農業包裝......檢查一下:

library(agricolae)

weight<-c( 68, 53, 69.5, 55, 71, 63, 76.5, 65.5, 69, 75, 76, 57, 70.5,
+ 71.5, 56, 81.5, 69, 59, 67.5, 61, 68, 59.5, 56.5, 73,
+ 61, 72.5, 71.5, 59.5, 74.5, 63)

h1<- graph.freq(weight,col="yellow",frequency=1,las=2,xlab="h1")

print(summary(h1),row.names=FALSE)

暫無
暫無

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

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