Reputation: 465
How do I efficiently turn a vector into a matrix so that the values of the vector determine the column and the element ordering determines the row, and the value assigned at those indices are determined afterwards.
X <- c(1,2,3,1,1,3)
Y <- 1:6
Z <- myfun(X, Y)
Z ## returns matrix
# 1 NA NA
# NA 2 NA
# NA NA 3
# 4 NA NA
# 5 NA NA
# NA NA 6
I am looking for a one-liner better than my for loop
Z0 <- X %o% rep(NA, length(unique(X)))
for(i in 1:length(Y)){ Z0[i, X[i]] <- Y[i] }
Upvotes: 0
Views: 442
Reputation: 48191
If you insist on a one-liner, then @djhurio's answer can be converted to
replace(matrix(NA, length(X), max(X)), cbind(1:length(X), X), Y)
# [,1] [,2] [,3]
# [1,] 1 NA NA
# [2,] NA 2 NA
# [3,] NA NA 3
# [4,] 4 NA NA
# [5,] 5 NA NA
# [6,] NA NA 6
Upvotes: 3
Reputation: 5536
See the example:
X <- c(1,2,3,1,1,3)
Y <- 1:6
myfun <- function(X, Y) {
Z <- matrix(NA, length(X), max(X))
Z[cbind(seq_along(X), X)] <- Y
Z
}
Z <- myfun(X, Y)
Z
Upvotes: 6