简体   繁体   中英

Why is recode in R not changing the original values?

I'm trying to use recode in R (from the car package) and it is not working. I read in data from a .csv file into a data frame called results . Then, I replace the values in the column Built_year , according to the following logic.

recode(results$Built_year, 
       "2 ='1950s';3='1960s';4='1970s';5='1980s';6='1990s';7='2000 or later'")

When I check results$Built_year after doing this step, it appears to have worked. However, it does not store this value, and returns to its previous value. I don't understand why.

Thanks.

(at the moment something is going wrong and I can't see any of the icons for formatting)

You need to assign to a new variable.

Taking the example from recode in the car package

R> x <- rep(1:3, 3)
R> x
[1] 1 2 3 1 2 3 1 2 3
R> newx <- recode(x, "c(1,2)='A'; else='B'")
R> newx
[1] "A" "A" "B" "A" "A" "B" "A" "A" "B"
R> 

By the way, the package is called car , not cars.

car::recode (and R itself) is not working as SPSS Recode function, so if you apply transformation on a variable, you must assign it to a variable, as Dirk said. I don't use car::recode , although it's quite straightforward... learn how to deal with factors... as I can see, you can apply as.numeric(results$Built_year) and get same effect. IMHO, using car::recode in this manor is trivial. You only want to change factor to numeric, right... Well, you'll be surprised when you see that:

> x <- factor(letters[1:10])
> x
 [1] a b c d e f g h i j
Levels: a b c d e f g h i j
> mode(x)
 [1] "numeric"
> as.numeric(x)
 [1]  1  2  3  4  5  6  7  8  9 10

And, boy, do I like answering questions that refer to factors... =) Get familiar with factors, and you'll see the magic of "recode" in R! =) Rob Kabacoff's site is a good starting point.

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