Reputation: 459
I have a list of indices and values as follows
1 3 2.1
2 1 1.1
2 2 0.2
2 3 0.4
1 2 0.3
1 1 3.2
3 3 4.0
3 1 0.2
3 2 0.1
where the first two columns represent the (i,j)'th index of a matrix that I wish to populate with the corresponding value. That is, I want the above to generate the following matrix
3.2 0.3 2.1
1.1 0.2 0.4
0.2 0.1 4.0
Is there a way to do this in R without resorting to a for loop?
Upvotes: 1
Views: 545
Reputation: 887951
An option would be to create a matrix
of 0s and fill the values of the third column of dataset with the indices from the first two columns
m1 <- matrix(0, 3, 3)
m1[as.matrix(df1[1:2])] <- df1[,3]
m1
# [,1] [,2] [,3]
#[1,] 3.2 0.3 2.1
#[2,] 1.1 0.2 0.4
#[3,] 0.2 0.1 4.0
Or with sparseMatrix
library(Matrix)
sparseMatrix(i = df1$col1, j = df1$col2, x = df1$col3)
# 3 x 3 sparse Matrix of class "dgCMatrix"
#[1,] 3.2 0.3 2.1
#[2,] 1.1 0.2 0.4
#[3,] 0.2 0.1 4.0
Another option is xtabs
xtabs(col3 ~ col1 + col2, df1)
# col2
#col1 1 2 3
# 1 3.2 0.3 2.1
# 2 1.1 0.2 0.4
# 3 0.2 0.1 4.0
If we need an efficient option may be dcast
library(data.table)
dcast(setDT(df1), col1 ~ col2, value.var = 'col3')
Or using tidyverse
library(tidyverse)
df1 %>%
spread(col2, col3)
NOTE: All the methods work even if there are unequal number of indices
df1 <- structure(list(col1 = c(1L, 2L, 2L, 2L, 1L, 1L, 3L, 3L, 3L),
col2 = c(3L, 1L, 2L, 3L, 2L, 1L, 3L, 1L, 2L), col3 = c(2.1,
1.1, 0.2, 0.4, 0.3, 3.2, 4, 0.2, 0.1)),
class = "data.frame", row.names = c(NA,
-9L))
Upvotes: 1
Reputation: 73802
You may bring the matrix in right order and apply matrix
.
matrix(m[order(m[,2], m[,1]), 3], 3)
# [,1] [,2] [,3]
# [1,] 3.2 0.3 2.1
# [2,] 1.1 0.2 0.4
# [3,] 0.2 0.1 4.0
Data
m <- structure(c(1, 2, 2, 2, 1, 1, 3, 3, 3, 3, 1, 2, 3, 2, 1, 3, 1,
2, 2.1, 1.1, 0.2, 0.4, 0.3, 3.2, 4, 0.2, 0.1), .Dim = c(9L, 3L
))
Upvotes: 1