2013-03-10 77 views
3

我有一个需要填充的计数的1维向量,称为count.array。我生成sample.array(可以比count数组更短或更长),但每个元素都在count数组的适当索引内。 R中最好的方式是总结每个元素出现的次数并将它们放入count数组中。计算R中样本的计数向量

我知道我可以通过一个for循环来做到这一点(通过sample.array,读取值,将1添加到索引),但也许有一个更聪明的R方法来做到这一点?

这里有一个工作示例:

count.array <- matrix(data = 0, nrow = 1, ncol = 10) 
sample.array <- matrix(data = c(5,2,4,5,2,4,3,4), nrow = 1, ncol =8) 

count.array[1,2] <- 2 
count.array[1,3] <- 1 
count.array[1,4] <- 3 
count.array[1,5] <- 2 

count.array 

回答

6

您可以使用table

freq <- table(sample.array) 

# sample.array 
# 2 3 4 5 <~~ names (use it for indexing) 
# 2 1 3 2 <~~ frequency (the values of your count.array) 

count.array[1, as.numeric(names(freq))] <- freq 

#  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] 
# [1,] 0 2 1 3 2 0 0 0 0  0 
+0

(+1)5秒太慢了:) – 2013-03-10 19:22:40