I have a large matrix (50 X 10,000) that contains integers representing the indices of vector values. I want to replace the integers representing the indices of vector values in the matrix with the actual vector values of the indices.
Here is the vector dat.full$year.total
of values:
[19] 13.51 20.56 20.03 18.33 24.30 19.65 13.99 18.84 18.61 18.70 18.39 13.80 25.89 13.08 17.19 17.90 19.44 20.51
[37] 21.22 15.98 14.23 11.85 16.08 14.02 16.44 20.25 15.58 29.09 11.11 20.29 23.99 26.23 15.75 18.65 22.65 18.64
[55] 22.70 17.11 21.22 14.16 27.41 17.15 16.01 10.91 15.25 18.45 27.43 19.28 18.85 15.30 22.39 12.77 16.95 11.47
[73] 19.47 11.13 24.89 16.19 27.52 16.65 18.69 18.43 20.21 15.11 18.24 14.66 13.49 23.82 24.20 13.45 16.91 21.54
[91] 24.51 18.54 17.44 21.35 25.82 16.95 20.62 21.70 21.17 17.38 21.87 16.79 29.93 21.38 28.49 22.29 25.88 15.96
[109] 18.28 13.88 22.02 27.17 17.52 19.31 17.13 17.02 22.19 20.32 22.29 15.65 34.15 23.57 27.39 17.25 21.89 19.01
[127] 15.89
The indices are 1 to 127. I tried using replace()
like mat<-matrix(replace(mat, row(dat.full), dat.full$year.total))
but this only gives a 1-column matrix. How do I achieve the desired replacements?
Thanks!
Suppose your matrix and vector looked like this:
mat <- matrix(9:1, ncol = 3)
vec <- as.numeric(mat * 20)/100
mat
#> [,1] [,2] [,3]
#> [1,] 9 6 3
#> [2,] 8 5 2
#> [3,] 7 4 1
vec
#> [1] 1.8 1.6 1.4 1.2 1.0 0.8 0.6 0.4 0.2
Then you simply do:
mat[] <- vec[mat]
So now mat
looks like this, with each element replaced by the corresponding entry in vec
mat
#> [,1] [,2] [,3]
#> [1,] 0.2 0.8 1.4
#> [2,] 0.4 1.0 1.6
#> [3,] 0.6 1.2 1.8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.