【问题标题】:recoding character variables重新编码字符变量
【发布时间】:2011-03-27 08:40:06
【问题描述】:

我正在尝试将字符变量重新编码为数值。

字符变量如下所示:

b <- c("Your category choice is correct", "Your category choice is incorrect", ...

我尝试了以下方法:

b_recoded <- ifelse(b = "Your category choice is correct",  
c(1), c(0))

我收到以下错误:

未使用的参数(b =“您的类别选择是正确的”)

我怎样才能让它工作?我正在尝试将"Your category choice is correct" 编码为1"Your category choice is incorrect" 编码为0

对不起,基本问题。我还在学习。

【问题讨论】:

    标签: r


    【解决方案1】:

    如果你的变量是字符,你可以使用正则表达式来匹配值:

    p <- "Your category choice is"
    s <- sample(c("correct", "incorrect"), 100, replace = TRUE)
    b <- paste(p, s)
    ( foo <- ifelse(grepl(" correct$", b), 1, ifelse(grepl(" incorrect$", b), 0, NA)) )
      [1] 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0 1 1 0 1 0 1 1 1 0 0 1 0 1 0 1 0 1 0 0 1 0 0
     [38] 1 1 1 1 0 0 1 0 0 0 0 1 1 0 1 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 0 0 1 1
     [75] 1 0 0 0 1 0 0 0 0 1 1 0 1 1 0 1 0 1 1 0 0 0 1 1 1 0
    

    【讨论】:

      【解决方案2】:

      ifelse 语句中的问题是您对逻辑表达式使用了单个等号。 = 用于 R 中的顶级左赋值。在函数调用中,这意味着您将参数 b 分配给 "Your category choice is correct"

      要得到一个逻辑表达式,你需要使用两个等号==。以下代码确实有效(使用 mropas 数据):

      b <- c(rep("Your category choice is correct", 3),
              rep("Your category choice is incorrect", 5),
              rep("Your category choice is correct", 2))
      
      b_recoded <- ifelse(b == "Your category choice is correct",  1, 0)
      

      另外请注意,我省略了 c() 函数,因为您不需要组合单个元素。

      如果您从 R 开始,通读其中一本入门手册或至少将其作为参考可能会很有用。这是我学习 R 时喜欢的一个:

      http://cran.r-project.org/doc/contrib/Paradis-rdebuts_en.pdf

      【讨论】:

      • 嘿,那是我第一本关于 R 的书。我记得当我的同事看了它一眼时,他们用那种眼神盯着我,就像:“你疯了吗?” =)
      【解决方案3】:

      数据:

      df <- c(rep("Your category choice is correct", 3),
              rep("Your category choice is incorrect", 5),
              rep("Your category choice is correct", 2))
      

      这会将您的 df 更改为 factor

      df2 <- factor(df, labels = c(1,0))   
      

      在开始时,因素的处理可能会有点混乱。因此,如果您更愿意将其保留为 numericinteger 类,您可以使用例如做

      df3 <- df
      df3[df3 == "Your category choice is correct"] <- 1
      df3[df3 == "Your category choice is incorrect"] <- 0
      df3 <- as.integer(df3)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多