代码之家  ›  专栏  ›  技术社区  ›  djq

为什么R中的recode不改变原始值?

  •  5
  • djq  · 技术社区  · 16 年前

    我试着用 recode car 包)并且它不工作。我从.csv文件中读取数据到一个名为 results Built_year ,根据以下逻辑。

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

    当我检查的时候 results$Built_year

    谢谢。

    2 回复  |  直到 12 年前
        1
  •  17
  •   Dirk is no longer here    16 年前

    你需要 分配

    以…为例 recode 在 car 包裹

    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> 
    

    顺便说一下,这个包叫做 汽车 ,而不是汽车。

        2
  •  4
  •   aL3xa    16 年前

    car::recode (和R本身)不是SPSS Recode函数,所以如果对变量应用转换,就必须将它赋给一个变量,正如Dirk所说。我不使用 ,虽然很简单。。。学习如何处理因素。。。如我所见,你可以申请 as.numeric(results$Built_year) 得到同样的效果。IMHO,使用 car::重新编码 在这个庄园里是微不足道的。你只想把因子改成数字,对吧。。。好吧,当你看到这一点时,你会惊讶的:

    > 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
    

    还有,孩子,我喜欢回答涉及因素的问题吗…=)熟悉这些因素,你就会看到R中“recode”的魔力!=) Rob Kabacoff's site