【问题标题】:Applying condition based on a list and create a new column based on the outcome r根据列表应用条件并根据结果 r 创建新列
【发布时间】:2020-09-05 01:27:57
【问题描述】:

我有一个清单如下:

c1 <-("apple", "tree", "husband")

还有这个数据:

df <-data.frame(
  ID = c("b","b","b","a","a","c"),
  col = c("husband", "apple", "juice", "happy", "husband", "white"),
)

我想要这个输出:

df <-data.frame(
  ID = c("b","b","b","a","a","c"),
  col = c("husband", "apple", "juice", "happy", "husband", "white"),
  c1 = c("1","1","0","0","1","0")
)

通过应用列表 (c1) 作为条件并且使用

mutate(c1= ifelse(col==happy | col==tree | col==husband,1,0))

谢谢

【问题讨论】:

    标签: r data-cleaning


    【解决方案1】:

    您可以使用%in% 来检查col 中的c1

    transform(df, c1 = as.integer(col %in% c1))
    #Even shorter
    #transform(df, c1 = +(col %in% c1))
    
    #  ID     col c1
    #1  b husband  1
    #2  b   apple  1
    #3  b   juice  0
    #4  a   happy  0
    #5  a husband  1
    #6  c   white  0
    

    在逻辑值上使用as.integer 比使用ifelse 更快:

    transform(df, c1 = ifelse(col %in% c1, 1, 0))
    

    【讨论】:

      【解决方案2】:

      你可以通过factor来玩花样,例如,

      within(df, out <- +!is.na(factor(col,levels = c1)))
      

      或通过%in%

      within(df, out <- +(col %in%c1))
      

      或通过match

      within(df,out <- 1-is.na(match(col,c1)))
      

      这样

        ID     col out
      1  b husband   1
      2  b   apple   1
      3  b   juice   0
      4  a   happy   0
      5  a husband   1
      6  c   white   0
      

      【讨论】:

        【解决方案3】:

        您还可以使用grepl() 来检查c1 中的任何值并直接分配给新变量:

        #Data 1
        c1 <- c("apple", "tree", "husband")
        #Data 2
        df <-data.frame(
            ID = c("b","b","b","a","a","c"),
            col = c("husband", "apple", "juice", "happy", "husband", "white"),stringsAsFactors = F)
        #Match and create new variable
        df$NewVar <- as.numeric(grepl(paste0(c1,collapse = '|'),df$col))
        

        输出:

          ID     col NewVar
        1  b husband      1
        2  b   apple      1
        3  b   juice      0
        4  a   happy      0
        5  a husband      1
        6  c   white      0
        

        【讨论】:

          【解决方案4】:

          case_when 的选项

          library(dplyr)
          df %>%
               mutate(c1 = case_when(col %in% c1, 1, 0))
          

          或者另一种选择是

          df %>%
              mutate(c1 = +(col %in% c1))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-10-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-22
            相关资源
            最近更新 更多