# Recoding Numeric Vector R

I have a numeric vector, let's say something like:

``x <- rep(1:6, 300)``

What I would like to do is recode the vector, in place such that 6=1,5=2,4=3,3=4,2=5,1=6. I don't want to create a factor out of it.

Everything I have tried so far gives me the wrong counts because of the order, ie:

``x[x == 6] <- 1x[x == 5] <- 2 ## Lines that follow where x[x == 2] removes 5's entirely from counts.``

Note: I'm aware of the car package, but would prefer to use base R for this problem.

Construct a map between the old and new values, and subset with the old,

``````(6:1)[x]
``````

Wouldn't something as simple as `7 - x` give you what you are after?

See manual for `car::recode`. Otherwise, create variable `y`:

``````y <- numeric()
length(y) <- length(x)
y[x == 6] <- 1
y[x == 5] <- 2
## ad nauseam...
``````

It's always considered a bad practice to recode variables in place, because if you mess things up, you're probably going to lose data. Be careful.

In your case, yes, just subtract. In general, `match` can be quite useful in cases like this. For example, suppose you wanted to recode the values in this `x` column to the values in the `y` column

``````> d <- data.frame(x=c(1,3,4,5 ,6),y=c(3,4,2.2,1,4.6))
> print(d, row.names=FALSE)
x   y
1 3.0
3 4.0
4 2.2
5 1.0
6 4.6
``````

Then this would recode the values in `a` to the new values.

``````> a <- c(3,4,6,1,5)
> d\$y[match(a,d\$x)]
 4.0 2.2 4.6 3.0 1.0
``````

`rev(x)` ... at least when the length is an even multiple of the sequence.

if you want to recode multiple variables you might take the following approach:

``````MapFunc = function(x) {
y = NULL;
if (x %in% c("1","2","3")) {y=100}
if (x %in% c("0","4")) {y=200}
if (x %in% c("5")) {y=100}
print(y)
}
MapFunc(x=1); MapFunc(x=0);   #working ok for scalars
``````
#
``````X = matrix( sample(0:5,25,replace=TRUE), nrow=5,ncol=5)
apply(X,c(1,2),MapFunc) #working ok for matrices...
``````