You could get the 'row/column' index by using match
, cbind
it and assign the 'timeStamp' elements to the positions specified by the index in 'mat'.
mat[cbind(match(x$meme, rownames(mat)),
match(x$webId, colnames(mat)))] <- x$timeStamp
mat
# 428 2679 68814 948
#2505 13 11 8 3
#2510 16 6 14 1
#2501 7 4 5 10
#2508 12 2 9 15
Checking with the results from the for
loop
for(i in 1:nrow(x))
mat1[rownames(mat1)==x[i,"meme"],
colnames(mat1)==x[i,"webId"]]<-x[i,"timeStamp"]
mat1
# 428 2679 68814 948
#2505 13 11 8 3
#2510 16 6 14 1
#2501 7 4 5 10
#2508 12 2 9 15
Benchmarks
set.seed(21)
x1 <- data.frame(meme= rep(sample(1000), each=200),
webId= rep(sample(35000, 200, replace=FALSE), 1000),
timeStamp=rnorm(1000*200))
set.seed(324)
mat2 <- matrix(, 1000, 200,
dimnames=list(sample(unique(x1$meme)),sample(unique(x1$webId))))
mat3 <- mat2
system.time({
mat2[cbind(match(x1$meme, rownames(mat2)),
match(x1$webId, colnames(mat2)))] <- x1$timeStamp
})
# user system elapsed
# 0.181 0.001 0.181
system.time({
for(i in 1:nrow(x1))
mat3[rownames(mat3)==x1[i,"meme"],
colnames(mat3)==x1[i,"webId"]]<-x1[i,"timeStamp"]
})
# user system elapsed
#172.588 10.445 183.062
identical(mat2, mat3)
#[1] TRUE
data
set.seed(24)
x <- data.frame(meme=rep(c(2501, 2505, 2508, 2510), each=4),
webId= rep(c(68814, 2679, 948, 428), 4), timeStamp= sample(16))
set.seed(33)
mat <- matrix(, 4, 4, dimnames=list(sample(unique(x$meme)),
sample(unique(x$webId))))
mat1 <- mat
mat[match(rownames(mat), x$meme), match(colnames(mat), x$webId)] <- x$timeStamp
[<-.data.frame
(*tmp*
, match(rownames(mat), x$meme), match(colnames(mat), : new columns would leave holes after existing columnsdput
to show the data, it would be great