Question

I know there must be an apply function or ave for this, but I am not quite sure how to do it:

I have data:

     date player market 
 1:  1-1      1      1    
 2:  1-1      2      1    
 3:  1-1      1      2    
 4:  1-2      2      1    
 5:  1-2      3      2    
 6:  1-3     21      1    
 7:  1-4      1      1    
 8:  1-4     51      1    
 9:  1-4      1      1    
10:  1-5      1      2    

I also have a blank array, which has unique dates on the rows, unique markets on the columns, and unique players for the third dimension.

1
[,,1]
    1  2
1-1
1-2
1-3
1-4
1-5


2
[,,2]
      1  2
1-1
1-2
1-3
1-4
1-5


etc

I want to fill out the array with from the data. I want each point to = 1 if the guy has an entry in the data where he is present for a date and market combination, and 0 if not. So for example, for 1 and 2, they would be filled out as:

1
[,,1]
    1  2
1-1 1 1
1-2 0 0
1-3 0 0
1-4 0 1
1-5 0 1


2
[,,2]
      1  2
1-1  1   0
1-2  1   0
1-3  0   0
1-4  0   0
1-5  0   0

Looping is out of the question. Thank you for your help.

Was it helpful?

Solution

You can use xtabs for this purpose. Where temp dates, Month market and day player.

data(airquality)
tab<-xtabs(~Temp+Month+Day,airquality)

> dim(tab)
[1] 40  5 31


> str(tab)
 xtabs [1:40, 1:5, 1:31] 0 0 0 0 0 0 0 0 0 0 ...
 - attr(*, "dimnames")=List of 3
  ..$ Temp : chr [1:40] "56" "57" "58" "59" ...
  ..$ Month: chr [1:5] "5" "6" "7" "8" ...
  ..$ Day  : chr [1:31] "1" "2" "3" "4" ...
 - attr(*, "class")= chr [1:2] "xtabs" "table"
 - attr(*, "call")= language xtabs(formula = ~Temp + Month + Day, data = airquality)

edit: converting to data frame.

> head(as.data.frame(tab))
  Temp Month Day Freq
1   56     5   1    0
2   57     5   1    0
3   58     5   1    0
4   59     5   1    0
5   61     5   1    0
6   62     5   1    0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top