Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap (translate) values inside a vector

Tags:

r

vector

swap

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:

  • 1 --> 3
  • 2 --> 4
  • 3 --> 2
  • 4 --> 1

I 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?

like image 471
Gilgamesh Avatar asked Feb 10 '18 18:02

Gilgamesh


People also ask

How do you swap items in a vector C++?

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.


2 Answers

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!

like image 163
Florian Avatar answered Oct 09 '22 18:10

Florian


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
like image 9
www Avatar answered Oct 09 '22 18:10

www