【问题标题】:calculate a count vector from a sample in R从 R 中的样本计算计数向量
【发布时间】:2013-03-10 19:17:26
【问题描述】:

我有一个需要填充的一维计数向量,称为 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

【问题讨论】:

    标签: arrays r counter


    【解决方案1】:

    你可以使用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
    

    【讨论】:

    • (+1),5 秒太慢了 :)
    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 2012-10-28
    • 2021-07-26
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多