简体   繁体   中英

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] <- 1 
x[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.

不会像7 - x那样简单的东西给你你想要的东西吗?

在旧值和新值之间构建映射,并使用旧值构建子集,

(6:1)[x]

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)]
[1] 4.0 2.2 4.6 3.0 1.0

rev(x) ...至少当长度是序列的偶数倍时。

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... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM