A[as.numeric(names(B))] <- B
Merge two vectors by element name
-
13-06-2023 - |
Domanda
I have two vectors:
> str(A)
Factor w/ 2 levels "neg","pos": 1 NA NA 1 1 2 NA NA 1 2 ...
> str(B)
Factor w/ 2 levels "neg","pos": 1 1 1 1 2 1 2 1 1 2 ...
- attr(*, "names")= chr [1:120] "2" "3" "7" "8" ...
and I need to merge them, such that the values from B get placed into A in the position determined by the name of the element in B. I tried
sapply(names(B), function(x) {
assign ("m", x)
A[x] <- B["m"] })
but the results are all weird:
2.NA 3.NA 7.NA 8.NA 12.NA 14.NA
<NA> <NA> <NA> <NA> <NA> <NA>
I think is some type of assignemnt problem but can't figure it out.
Soluzione
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow