Reputation: 95
I am currently trying to convert this data set of team scores:
week AwayTeam AwayScore HomeTeam HomeScore
1 1 A 1 B 1
2 1 C 0 D 1
3 2 A 1 D 0
4 2 B 1 C 0
5 3 C 4 A 0
6 3 D 2 B 2
Into a matrix that looks something like this:
A = matrix(c(1,-1,0,0,
0,0,1,-1,
1,0,0,-1,
0,1,-1,0,
-1,0,1,0,
0,-1,0,1),6,4,byrow = TRUE)
The rows of matrix A works as follows: "1" equals the away team, "-1" equals the home team, and "0" is the remaining space in each row. The first row of matrix A, therefore, is team A (away) versus team B (home).
If anyone could help convert this data into a matrix like this, it would be greatly appreciated.
Upvotes: 1
Views: 37
Reputation: 101403
You can try the code below
v <- LETTERS[1:4]
A <- matrix(0,nrow = nrow(df),ncol = 4)
A[cbind(1:nrow(df),match(df$AwayTeam,v))] <- 1
A[cbind(1:nrow(df),match(df$HomeTeam,v))] <- -1
such that
> A
[,1] [,2] [,3] [,4]
[1,] 1 -1 0 0
[2,] 0 0 1 -1
[3,] 1 0 0 -1
[4,] 0 1 -1 0
[5,] -1 0 1 0
[6,] 0 -1 0 1
DATA
df <- structure(list(week = c(1L, 1L, 2L, 2L, 3L, 3L), AwayTeam = c("A",
"C", "A", "B", "C", "D"), AwayScore = c(1L, 0L, 1L, 1L, 4L, 2L
), HomeTeam = c("B", "D", "D", "C", "A", "B"), HomeScore = c(1L,
1L, 0L, 0L, 0L, 2L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
Upvotes: 1