在R中从样本计算计数向量

3
我有一个计数的一维向量需要填充,名为count.array。我生成了一个sample.array(可以比count数组短或长),但每个元素都在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
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接