Joining a vector and a matrix up in base R

75 Views Asked by At

I have the following:

M looks like:

     [,1]
[1,]    1
[2,]    0
[3,]    2
[4,]    3
[5,]    0
[6,]    4
[7,]    5
[8,]    0

and

out looks like

         1          2          3          4          5 
0.03674056 0.04589834 0.11752682 0.15196921 0.15641792

I want to join the out up to the first column in M [, 1]

The size of out and M should be the same.

Expected output:

    [,1]     [, 2]
[1,]    1    0.03674056
[2,]    0    0
[3,]    2    0.04589834
[4,]    3    0.11752682
[5,]    0    0
[6,]    4    0.15196921
[7,]    5    0.15641792
[8,]    0    0

Data

M = structure(c(1, 0, 2, 3, 0, 4, 5, 0), dim = c(8L, 1L))
out = c(`1` = 0.0367405608512068, `2` = 0.0458983425258914, `3` = 0.117526821260374, 
`4` = 0.151969207752795, `5` = 0.156417915745223)
3

There are 3 best solutions below

0
r2evans On
M = structure(c(1, 0, 2, 3, 0, 4, 5, 0), dim = c(8L, 1L))
out = c(`1` = 0.0367405608512068, `2` = 0.0458983425258914, `3` = 0.117526821260374, 
`4` = 0.151969207752795, `5` = 0.156417915745223)
vec <- setNames(c(0.03674056, 0.04589834, 0.11752682, 0.15196921, 0.15641792), 1:5)

cbind(M, c(vec, 0)[match(M[,1], names(vec), nomatch = length(vec)+1)])
#   [,1]       [,2]
# 1    1 0.03674056
#      0 0.00000000
# 2    2 0.04589834
# 3    3 0.11752682
#      0 0.00000000
# 4    4 0.15196921
# 5    5 0.15641792
#      0 0.00000000
2
Waldi On

Other solution:

M2 <- M
M2[M!=0]<- out[M[M!=0]]
cbind(M,M2)

     [,1]       [,2]
[1,]    1 0.03674056
[2,]    0 0.00000000
[3,]    2 0.04589834
[4,]    3 0.11752682
[5,]    0 0.00000000
[6,]    4 0.15196921
[7,]    5 0.15641792
[8,]    0 0.00000000
0
jblood94 On
cbind(M, c(0, out)[M + 1])
#>   [,1]       [,2]
#> 1    1 0.03674056
#>      0 0.00000000
#> 2    2 0.04589834
#> 3    3 0.11752682
#>      0 0.00000000
#> 4    4 0.15196921
#> 5    5 0.15641792
#>      0 0.00000000