Reputation: 610
how to effectivly iterate matrix? I must be able to get rows and columns names.
My current code (it works):
m <- matrix(1:9,3,3,FALSE,dimnames = list(c("x1","x2","x3"),c("y1","y2","y3")))
for(row in 1:nrow(m)) {
for(col in 1:ncol(m)) {
print(paste(
dimnames(m)[[1]][row], dimnames(m)[[2]][col],", value:", m[row,col],sep=" "
))
}
}
Upvotes: 0
Views: 66
Reputation: 43344
A fully-vectorized option is to make the indices with outer
, then paste
on the rest and assign the results back to the matrix structure:
m <- matrix(1:9, 3, 3, FALSE, dimnames = list(c("x1","x2","x3"), c("y1","y2","y3")))
m2 <- m # don't overwrite m
m2[] <- paste(outer(rownames(m), colnames(m), paste), 'value:', m)
m2
#> y1 y2 y3
#> x1 "x1 y1 value: 1" "x1 y2 value: 4" "x1 y3 value: 7"
#> x2 "x2 y1 value: 2" "x2 y2 value: 5" "x2 y3 value: 8"
#> x3 "x3 y1 value: 3" "x3 y2 value: 6" "x3 y3 value: 9"
If you prefer, you could use the results to reconstruct a new matrix instead of overwriting an existing one, pulling nrow
, ncol
, and dimnames
from m
:
m2 <- matrix(paste(outer(rownames(m), colnames(m), paste), 'value:', m),
nrow(m), ncol(m), dimnames = dimnames(m))
The results are identical.
Upvotes: 2
Reputation: 206242
You can just use mapply
here
mapply(function(v, r, c) {paste(v, r, c)},
m, rownames(m)[row(m)], colnames(m)[col(m)])
But whether or not that's a good idea really depends on why you think you need to explicitly iterate over the values in the matrix. There are many functions that can work without having to explicitly write a loop.
Upvotes: 3