# Write values from one vector in another with char var as ID

Hi,
I have the following problem - I have one vector (variance_vec) which has variances for different materials in it (created by a tapply loop) which looks like:

``````Material A    0.8
Material B    0.21
.
.
.
``````

Now I have another vector (mat_vec) which has random draws of materials in it, like:

``````Material A
Material D
Material B
Materrial A
.
.
.
``````

I know want to assign the variance to every material in the mat_vec vector.
I tried it like:

``````#1
mat_vec_var<- variance_vec[[mat_vec]]
#2
``````

Both methods did not work for vectors.
How would I need to adjust my code to get a vector of variances for the randomly drawn materials? I know how I could do it in a loop but there are lots of observations in the vecotors so I would like to not use a loop for that.
Thanks for the help!

Hi,

If i understood correctly, I would go like that

``````# with vectors
variance_vec <- c('Material A' = 0.8,  'Material B' = 0.21)
mat_vect <- c('Material A',
'Material D',
'Material B',
'Material A')

variance_vec[mat_vect]
#> Material A       <NA> Material B Material A
#>       0.80         NA       0.21       0.80
``````

Also, in such case, I would work with data.frame and use dplyr and other tidyverse. I could really help once the case become more complex than simple vetor.
You have nice join fonctions that works well.

``````library(dplyr)
# using enframe to simplify vector -> df transformation
variance_df <- tibble::enframe(variance_vec)
variance_df
#> # A tibble: 2 x 2
#>   name       value
#>   <chr>      <dbl>
#> 1 Material A  0.8
#> 2 Material B  0.21
# this is like a data.frame but with nice printing
mat_df <- tibble(name = mat_vect)
mat_df
#> # A tibble: 4 x 1
#>   name
#>   <chr>
#> 1 Material A
#> 2 Material D
#> 3 Material B
#> 4 Material A
# table operation : join
mat_df %>%
left_join(variance_df, by = 'name')
#> # A tibble: 4 x 2
#>   name       value
#>   <chr>      <dbl>
#> 1 Material A  0.8
#> 2 Material D NA
#> 3 Material B  0.21
#> 4 Material A  0.8
``````

Created on 2019-05-07 by the reprex package (v0.2.1.9000)

1 Like

Thanks for the help, that solved it!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.