Ben
Ben

Reputation: 64

count values in matrix column in R

I am running a simulation of a lottery style draft which creates a matrix of x# of possible orders. The columns are the picks (e.g. first column is pick 1, second column is pick 2 ect.) I am trying to count the number times each Team gets each pick by counting the columns. However using the table function I can display the values, but can't figure out how to store them into a matrix/vector. Here is a sub set of the code I currently have.

tickets = c("A","B","B","C","C","C","D","D","D","D")#Population to draw
df <- matrix(data=NA,nrow=100,ncol=4)# row = #trials, col = # teams

for ( i in 1:100)
#block of code to run
{
order= c(sample(tickets,10,FALSE,))
temp = unique(order)
df[i,] = temp
} #draw all the tickets and delete duplicate values

one = table(df[,1]) #count number times each team gets 1st pick
one # display 
 A  B  C  D 
12 18 26 44 

I would like to put the values from each column into vectors and then into a matrix to run probabilities.

Upvotes: 1

Views: 2440

Answers (1)

Rorschach
Rorschach

Reputation: 32446

You can split by column (since its a matrix, otherwise if it's a data.frame or list, just sapply), then tabulate

sapply(split(df, col(df)), table)
#    1  2  3  4
# A 10 12 23 55
# B 19 27 32 22
# C 32 28 21 19
# D 39 33 24  4

Upvotes: 1

Related Questions