I'm trying to parse the coordinates of a matrix from a vector to retrieve an element.
Data:
m <- matrix(1:25, ncol = 5)
v <- c(2,3)
I'm basically trying to get the elementm[2,3]
, in that case the value 12, by parsing the vector as coordinates:
m[v]
but all I get is NA
. I have tried m[paste(v, collapse="\",\""]
, which also did not work.
I know I could use
m[paste(v[1]), paste(v[2])]
but I'm trying to find a more elegant solution.
Any idea how to get this to work?
CodePudding user response:
you can try
> m[matrix(v, 1)]
[1] 12
or just
> m[t(v)]
[1] 12
CodePudding user response:
Few more options:
m[v[1], v[2]]
[1] 12
do.call("[", c(list(m), as.list(v)))
[1] 12
m[v[1] (v[2]-1) * nrow(m)]
[1] 12