calculate a count vector from a sample in R
arrays, counter, r
Solution
You can use `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
Problem
I have a 1 dimensional vector of counts that I need to populate, called count.array. I generate sample.array (that can be shorter or longer than count array) but where every element is within an appropriate index of count array. What's the best way in R to sum up how many times each element occurs and put them into count array. I realize I can do this with one for loop (go through sample.array, read the value, add 1 to the index) but perhaps there is a smarter R way to do it? Here's a working example: ``` 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 ```