Let
vetA <- c(1,2,1,2,1,3,4,1,2,3,2,1,4)
What are the possibilities so I could do the following swap? Swap:
-->
3 -->
4-->
2-->
1I have tried this:
vetB <- as.factor(vetA)
levels(vetB) <- c(3,4,2,1)
vetA <- as.integer(vetB)
# because
print(vetB)
# [1] 3 4 3 4 3 2 1 3 4 2 4 3 1
#Levels: 3 4 2 1
It didn't work. Could you please give me a hand?
The std::swap() is a built-in function in C++ STL which swaps the value of any two variables passed to it as parameters. The std::vector::swap() function is used to swap the entire contents of one vector with another vector of same type.
One possible option would be to use match
:
vetA <- c(1,2,1,2,1,3,4,1,2,3,2,1,4)
old=c(1,2,3,4)
new=c(3,4,2,1)
new[match(vetA,old)]
Output:
3 4 3 4 3 2 1 3 4 2 4 3 1
Hope this helps!
If you converted your factor vector to character before converting it to integer, your code will work. Notice that factor is internally stored as integer, so as.integer(vetB)
would return its integer levels.
vetA <- c(1,2,1,2,1,3,4,1,2,3,2,1,4)
vetB <- as.factor(vetA)
levels(vetB) <- c(3,4,2,1)
vetA <- as.integer(as.character(vetB))
vetA
# [1] 3 4 3 4 3 2 1 3 4 2 4 3 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With