ABC
ABC

Reputation: 11

How do I count / display the number of each outcome from a random sample?

I'm taking a sample of size 1000 of different (pet) animals. My code is

pet <- sample(c("dog","cat","hamster","goldfish"), 1000, replace = TRUE)

I want to see how many times "dog" was selected, "cat" was selected, etc. I've tried summary(pet) but wasn't much help / just told me it is length 1000 and characters.

Upvotes: 0

Views: 1546

Answers (2)

gung - Reinstate Monica
gung - Reinstate Monica

Reputation: 11903

The way you are creating this variable creates a vector of character data. Consider:

> pet <- sample(c("dog","cat","hamster","goldfish"), 1000, replace = TRUE)
> str(pet)
 chr [1:1000] "cat" "dog" "dog" "goldfish" "dog" "dog" ...

You need a factor vector with specific levels. Try:

> summary(as.factor(pet))
     cat      dog goldfish  hamster 
     252      244      252      252 

Upvotes: 1

rnso
rnso

Reputation: 24623

Try in R:

> table(pet)
pet
     cat      dog goldfish  hamster 
     241      284      225      250 

Upvotes: 3

Related Questions