开发者

In R, how do you count the character vectors?

I used sample function in R to generate a sample of 100 fair coin flips, here is the commands i used.

fair.coin = c("heads" = 0.5, "tails" = 0.5)

then,

x <- sample(fair.coin, size = 100, replace = TRUE)
> x

tails tails tails heads tails tails tails heads heads tails heads heads tails tails

  0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   开发者_StackOverflow中文版0.5   0.5   0.5   0.5 

heads tails heads tails tails tails tails heads heads heads heads tails heads tails 

  0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5 

tails tails tails heads heads heads heads heads heads heads tails heads tails tails 

  0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5 

tails heads tails heads heads heads tails tails heads tails tails heads heads heads 

  0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5 

heads tails tails tails heads heads tails tails tails heads heads heads heads tails 

  0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5 

tails heads heads heads tails tails tails heads heads heads tails heads tails tails 

  0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5 

heads tails heads heads tails heads tails tails tails heads heads heads tails heads 

  0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5   0.5 

tails tails 

  0.5   0.5 

That's what I'm getting right now. And I am looking to find the total number of heads that is in this sample, how could I do that? I tried sum(x>0.5), x[-tails] and so on, they are all counting the numbers (since they are fair, all r 0.5), instead of the names of the vector. Is there any functions in R I can use to count the number of heads in this 100 samples?

Thanks in advance!


Don't know what you're trying to do, but this works on your data

length(x[names(x)=="tails"])
[1] 45

or

> table(names(x))

heads tails 
   55    45 

Still, your data looks very puzzling to me. It is not even a character vector, it is a numeric vector with names. Is it possible you're trying something like :

> x <-  sample(c("heads","tails"),
+        size=100,
+        replace = TRUE,
+        prob=c(0.5,0.5)
+       )

> length(x[x=="tails"])
[1] 43

> table(x)
x
heads tails 
   57    43 


table(names(x))

Incidentally, you would be better to use,

x <- sample(c("heads","tails"),size=100,replace=T)

to generate this data. Then you could use table(x).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜