Unir un vector y una matriz en base R

Resuelto user113156 asked hace 54 años • 0 respuestas

Tengo lo siguiente:

M se parece a:

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

y

parece

         1          2          3          4          5 
0.03674056 0.04589834 0.11752682 0.15196921 0.15641792

Quiero unirme outa la primera columna en M[, 1]

El tamaño de outy Mdebe ser el mismo.

Rendimiento esperado:

    [,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

Datos

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)
user113156 avatar Jan 01 '70 08:01 user113156
Aceptado
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
jblood94 avatar Feb 15 '2024 21:02 jblood94

Otra solución:

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
Waldi avatar Feb 15 '2024 21:02 Waldi
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
r2evans avatar Feb 15 '2024 21:02 r2evans