【问题标题】:Recode variable in R based on first characters of vector根据向量的第一个字符在 R 中重新编码变量
【发布时间】:2018-07-19 14:13:53
【问题描述】:

我有一个如下所示的数据框:

codes <- c('TFAA1', 'TFAA2', 'TFAA3', 'TFAA4', 'TFAB1', 'TFAB2', 'TFAB3', 'TFAB4')
scores <- c(4,3,2,2,4,5,1,2)
example <- data.frame(codes, scores)

我想创建一个名为 code_group 的新列,其中以 TFAA 开头的所有内容都称为“Group1”,而以 TFAB 开头的所有内容都称为“Group2”。

一直在使用 car 包中的 recode 功能和 grepl 功能,但我失败得很惨。到目前为止,这是我的尝试......

recode <- (codes, "%in% TFAA='Group1'; %in% TFAB='Group2'")

【问题讨论】:

    标签: r recode


    【解决方案1】:

    使用dplyrstringr 你可以完成它:

    library(dplyr)
    library(stringr)
    example %>% 
      mutate(code_group = case_when(str_detect(codes, "^TFAA") ~ "Group1",
                                  str_detect(codes, "^TFAB") ~ "Group2"))
    

    case_when 允许您使用多个 if-then 情况。 str_detect 可以让您检测您在字符串中寻找的模式。

    【讨论】:

    • startsWith 当然可以替代str_detect
    【解决方案2】:
    example$code_group <- ifelse(startsWith(codes, 'TFAA'), 'Group 1', 
                          ifelse(startsWith(codes, 'TFAB'), 'Group 2',
                                 NA))
    

    【讨论】:

      【解决方案3】:

      我们可以使用substr 提取前四个字符,将其转换为factor 并指定labels 作为我们想要的字符

      example$code_group <-  with(example,  as.character(factor(substr(codes, 1, 4), 
                    levels = c('TFAA', 'TFAB'), labels = c('Group1', 'Group2'))))
      

      【讨论】:

        【解决方案4】:

        我们可以使用split&lt;-

        example$group <- NA
        split(example$group,substr(example$codes,1,4)) <- paste0("Group",1:2)
        example
        #   codes scores  group
        # 1 TFAA1      4 Group1
        # 2 TFAA2      3 Group1
        # 3 TFAA3      2 Group1
        # 4 TFAA4      2 Group1
        # 5 TFAB1      4 Group2
        # 6 TFAB2      5 Group2
        # 7 TFAB3      1 Group2
        # 8 TFAB4      2 Group2
        

        或者我们可以将因子用于相同的输出(3 个变体):

        example$group <- paste0("Group",factor(substr(example$codes,1,4),,1:2))
        example$group <- paste0("Group",as.numeric(factor(substr(example$codes,1,4))))
        example$group <- factor(substr(example$codes,1,4),,paste0("Group",1:2))
        

        在最后一种情况下,您将获得一个因子列,在所有其他情况下,您将获得一个字符列。

        【讨论】:

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