Creating an array with data conditional on another matrix

Multi tool use
Creating an array with data conditional on another matrix
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.
1 Answer
1
You can use xtabs
for this purpose. Where temp dates, Month market and day player.
xtabs
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
In this case you shoud have three id columns and dummy variable (0-1) denoting which interaction of id variables exists. Code
as.data.frame(tab)
gives me the "flat" data frame.– Maciej
Mar 16 '14 at 18:16
as.data.frame(tab)
What version of R are you using?
– Maciej
Mar 16 '14 at 18:28
let us continue this discussion in chat
– Maciej
Mar 16 '14 at 18:35
You coud use
data.table
package library(data.table); tab1<-as.data.table(tab); tab1
– Maciej
Mar 16 '14 at 18:50
data.table
library(data.table); tab1<-as.data.table(tab); tab1
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Beautiful! Cross-tabulation is amazing! Thank you!
– wolfsatthedoor
Mar 16 '14 at 6:53