【问题标题】:add new column based on two other columns with several conditions, character基于具有多个条件的其他两列添加新列,字符
【发布时间】:2022-01-17 03:49:52
【问题描述】:

我想根据另外两列向我的数据框添加一个新列。数据如下:

df
job    honorary  

yes    yes
yes    no
no     yes
yes    yes
yes    NA
NA     no

现在我想要第三列包含“both”如果 job 和 Honorary 是 yes,“honorary”如果只有 honourary 列包含 yes,“job”如果只有列 job 包含 yes,如果两者都包含 NA包含 NA 或一列包含 NA 而另一列没有。第三列应如下所示:

result

both
job
honorary
both
job
NA

我尝试过使用 if 和 mutate 的代码,但我对 R 很陌生,而且我的代码根本不起作用。 如果我像这样单独分配值:

data_nature_fewmissing$urbandnat[data_nature_fewmissing$nature =="yes" & data_nature_fewmissing$urbangreen =="yes"] <- "yes"

它不起作用,因为在每一步中我都会覆盖之前的结果。

感谢您的帮助!

【问题讨论】:

    标签: r conditional-statements multiple-columns add


    【解决方案1】:

    对于这些类型的复杂条件,我喜欢 dplyr 中的 case_when。

    df<-tibble::tribble(
       ~job, ~honorary,
      "yes",     "yes",
      "yes",      "no",
       "no",     "yes",
      "yes",     "yes",
      "yes",        NA,
         NA,      "no"
      )
    
    library(dplyr)
    
    df_new <- df %>%
      mutate(result=case_when(
        job=="yes" & honorary=="yes" ~ "both",
        honorary=="yes" ~ "honorary", 
        job=="yes" ~ "job", 
        is.na(honorary) & is.na(job) ~ NA_character_, 
        is.na(honorary) & job=="no" ~ NA_character_, 
        is.na(job) & honorary=="no" ~ NA_character_, 
        TRUE ~ "other"
      ))
    
    df_new
    #> # A tibble: 6 × 3
    #>   job   honorary result  
    #>   <chr> <chr>    <chr>   
    #> 1 yes   yes      both    
    #> 2 yes   no       job     
    #> 3 no    yes      honorary
    #> 4 yes   yes      both    
    #> 5 yes   <NA>     job     
    #> 6 <NA>  no       <NA>
    

    或在基础R中

    
    df_new<-df
    
    df_new=within(df_new,{
      result=NA
      result[ honorary=="yes"] = "honorary"
      result[ job=="yes"] = "job"
      result[job=="yes" & honorary=="yes"]='both'
    })
    

    由reprex package (v2.0.1) 于 2022-01-16 创建

    【讨论】:

    • 感谢您的完美工作!
    • @Joe Erinjeri,很好!只是好奇,你能不能想出一个只使用 base R 的解决方案?可以使用多个ifelse 语句,但必须有一种更有效的方法...
    • 添加了基础 r 解决方案。请注意,在 base r 中使用 within,它会将值分配给组内每个条件的数据框。所以你基本上覆盖了最初设置的 NA 。这就是我喜欢 dplyr 解决方案的原因,因为它是一种更简洁的方式来编写多个 if else。
    【解决方案2】:

    您的代码返回错误,因为您没有为行编制索引。索引数据帧时,语法为df[rows, columns]。所以要索引行并选择所有列,你必须添加一个逗号:

    data_nature_fewmissing$urbandnat[data_nature_fewmissing$nature =="yes" &amp; data_nature_fewmissing$urbangreen =="yes",] &lt;- "yes"

    然而,一个更简单的方法是使用 tidyverse。我们将使用mutate 创建新列,使用case_when 处理多个 if-else 条件。

    library(tidyverse)
    
    df = data_nature_fewmissing
    df %>% mutate(result = case_when(
      job == 'yes' & honorary == 'yes' ~ 'both', 
      job == 'yes' & (honorary == 'no' | is.na(honorary)) ~ 'job',
      honorary == 'yes' & (job == 'no' | is.na(job)) ~ 'honorary',
      )) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-05
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 2020-11-01
      • 2017-10-06
      相关资源
      最近更新 更多