Reputation: 11
I am attempting to make a simple table in R. The data I have is
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.
What I want to do is create 6 equal intervals from 5 to 35 and count how many numbers are in each interval. Then I want to create a table that shows the frequency, relative frequency, and percentage for each interval. I want something that looks like this:
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
I've tried this
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)
but it doesn't work.
Upvotes: 1
Views: 341
Reputation: 43364
There are a number of ways to do this, but start with cut
ting the data into bins, upon which you can call table
. as.data.frame.table
returns a data.frame very close to what you want. You can use prop.table
to add the relative
column; and the percent
is just that times 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
Upvotes: 1