Why is recode in R not changing the original values?

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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)

回答1:

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.



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!