【问题标题】:Is there a way to turn categorical variables into a number (R)?有没有办法将分类变量变成数字(R)?
【发布时间】:2021-06-22 15:53:41
【问题描述】:

我在 R 上有一个数据集(从 Excel 导入),它有一列用于分类变量“性别”,响应为男性和女性,我想将它们更改为 1 和 2,即。男=1,女=2,请问我该怎么做? (旁注:我正在使用 RStudio)

【问题讨论】:

  • ifelse(df$sex == 'male',1,2) 可以解决问题。

标签: r categorical-data dummy-variable


【解决方案1】:

其实方法有很多:

as.integer(factor(x, levels = c("male", "female")))

c(1, 2)[1 + (x == "female")]

match(x, c("male", "female"))

ifelse(x == "male", 1, 2)

【讨论】:

    【解决方案2】:

    您可以使用replace 函数将一个值替换为另一个值。这里有 1 或 2(有“”,就是字符值)。

    这里是一个例子:

    x <- c("male", "female", "male", "male", "male", "female", "female", "male")
    
    x <- replace(x, x=="male", "1")
    x <- replace(x, x=="female", "2")
    
    x
    
    

    【讨论】:

      【解决方案3】:

      as.numeric(factor(x))

      会工作的。确实有很多方法可以给这只猫剥皮。

      更好的可能只是

      factor(x)

      虽然我不确定你的下一步是什么。

      【讨论】:

        【解决方案4】:

        可以定义一个自定义函数,然后使用lapply() 应用它,它对特定的df 列执行操作:

        # some random data #
        df <- data.frame(sex=c('male', 'female', 'male', 'female'))
        
        encode_fun <- function(x){
         if(x=='female'){
          return(2)
        } else if(x=='male'){
          return(1)
        } else {
          return(NA)
        }
        }
        
        
        df$sex <- do.call(rbind, lapply(df$sex, encode_fun))
        

        另外,通过结合 mutate() 函数执行转换和 case_when() 作为来自 library(dplyr) 的逻辑运算符的函数:

        library(dplyr)
        
        df %>%
          dplyr::mutate(sex = case_when(sex == 'male' ~ 1,
                                  sex == 'female' ~ 2))
        
        

        可以通过使用library(stringr) 中的str_replace() 函数来完成字符串方法

        library(stringr)
        library(dplyr)
        
        df %>%
          dplyr::mutate(sex = str_replace(sex, '^male', '1')) %>%
          dplyr::mutate(sex=str_replace(sex, '^female$', '2')) %>%
          dplyr::mutate(sex = as.numeric(sex))
        

        【讨论】:

          猜你喜欢
          • 2021-04-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-16
          • 2021-08-12
          • 2021-05-15
          • 2021-06-10
          • 2021-01-04
          相关资源
          最近更新 更多