Reputation: 3
Suppose I have 30 trials of 1, 40 trials of 2 and 50 trials of 3. If I use this code:
library(lattice)
a <- c(30,40,50)
histogram(a)
Then the numbers of results will be presented as range instead of frequency. Is there a more convenient way than listing 3 for 50 times?
Edit: In an experiment, researchers are figuring out how many times phones would be broken after falling. 30 phones broke after 1st trial, 40 after 2nd and 50 after 3rd. So I would like to present this tendency. However, after I did with the previous code, the graph looked like following: graph Here R treated my data as one case. Thus I am looking for some ways to make these data appeared as frequencies of cases.
Upvotes: 0
Views: 173
Reputation: 173813
I think barplot
is the best way to achieve this, as others have said in the comments, but it looks as though you would also like to know a way to "un-table" the counts to create a histogram. You can do this by using rep
:
a <- rep(1:3, c(30, 40, 50))
a
#> [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
#> [35] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
#> [69] 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
#> [103] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
which you could plot with a histogram if you really wanted, like this:
hist(a, breaks = 0:3 + .5, main = "frequency", xlab = "n", axes = FALSE)
axis(side = 2, at = 0:5 * 10)
axis(side = 1, at = 1:3)
However, a histogram isn't really what you want here. A histogram is a way of counting continuous data by putting it into "bins", so in a histogram, the x axis is continuous. Plotting it this way implies that it was possible to break a phone 1.6 times or 2.38 times.
If you want to display counts of discrete events, you should use a bar plot. This has the advantages of being appropriate for count data, and being much easier to create:
barplot(c(30,40,50), names.arg = 1:3, col = "lavender", main = "Broken phones")
Upvotes: 1