制作简单的频率表

时间:2018-01-17 05:55:25

标签: r

我试图在R中创建一个简单的表。我的数据是

9, 28, 14, 29, 21, 27, 15, 23, 23, 10, 31, 23, 
16, 26, 22, 17, 19, 24, 21, 20, 26, 20, 16, 14, 21.

我想要做的是从5到35创建6个相等的间隔,并计算每个间隔中的数量。然后我想创建一个表格,显示每个区间的频率,相对频率和百分比。我想要一些看起来像这样的东西:

Interval   Frequency   Relative Frequency   Percentage
[5, 10]     2           .08                  8
(10, 15]    3           .12                  12
(15, 20]    6           .24                  24
(20, 25]    8           .32                  32
(25, 30]    5           .2                   2
(30, 35]    1           .04                  4

我试过这个

data <- c(9, 28, 14, 29, 21, 27, 15, 23, 23, 10, 31, 23, 16, 26, 22, 
17, 19, 24, 21, 20, 26, 20, 16, 14, 21)
intervals = c('[5, 10]', '(10, 15]', '(15, 20]', '(20, 25]', '(25, 
30]', '(30, 35]')
frequencies <- hist(data, breaks=seq(5,35,l=7))
table(intervals, frequencies$counts, frequencies$density * 5, 
frequencies$density * 500)

但它不起作用。

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点,但首先要将cut数据放入垃圾箱,您可以在其中调用tableas.data.frame.table返回一个非常接近您想要的data.frame。您可以使用prop.table添加relative列;而percent就是100倍。

x <- c(9, 28, 14, 29, 21, 27, 15, 23, 23, 10, 31, 23, 16, 26, 22, 17, 19, 24, 21, 20, 26, 20, 16, 14, 21)

df <- as.data.frame(table(cut(x, seq(5, 35, 5))))
df$relative <- prop.table(df$Freq)
df$percent <- df$relative * 100

df
#>      Var1 Freq relative percent
#> 1  (5,10]    2     0.08       8
#> 2 (10,15]    3     0.12      12
#> 3 (15,20]    6     0.24      24
#> 4 (20,25]    8     0.32      32
#> 5 (25,30]    5     0.20      20
#> 6 (30,35]    1     0.04       4