elo*_*esp 28 r frequency histogram cumulative-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
Run Code Online (Sandbox Code Playgroud)
像这样的表:
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
Run Code Online (Sandbox Code Playgroud)
我知道它应该很简单,但我不知道如何.
我使用此代码获得了一些结果:
factorx <- factor(cut(x, breaks=nclass.Sturges(x)))
as.matrix(table(factorx))
Run Code Online (Sandbox Code Playgroud)
Cha*_*ase 26
你很亲密!有一些功能可以让你轻松,即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
Run Code Online (Sandbox Code Playgroud)
42-*_*42- 22
该基地的功能table,cumsum并且prop.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
Run Code Online (Sandbox Code Playgroud)
有了cbind并根据自己的喜好命名列,这对你来说应该很容易.表函数的输出是一个矩阵,因此该结果也是一个矩阵.如果这是在一个大的东西上完成,那么这将是更有效的:
tbl <- table(x)
cbind( Freq=tbl, Cumul=cumsum(tbl), relative=prop.table(tbl))
Run Code Online (Sandbox Code Playgroud)
San*_*att 12
如果您正在寻找预包装的产品,请考虑包装中的freq()功能descr.
library(descr)
x = c(sample(10:20, 44, TRUE))
freq(x, plot = FALSE)
Run Code Online (Sandbox Code Playgroud)
或者要获得累积百分比,请使用该ordered()功能
freq(ordered(x), plot = FALSE)
Run Code Online (Sandbox Code Playgroud)
要添加"累积频率"列:
tab = as.data.frame(freq(ordered(x), plot = FALSE))
CumFreq = cumsum(tab[-dim(tab)[1],]$Frequency)
tab$CumFreq = c(CumFreq, NA)
tab
Run Code Online (Sandbox Code Playgroud)
如果您的数据缺少值,则会向表中添加有效的百分比列.
x = c(sample(10:20, 44, TRUE), NA, NA)
freq(ordered(x), plot = FALSE)
Run Code Online (Sandbox Code Playgroud)