【问题标题】:New column based on multiple line conditions基于多行条件的新列
【发布时间】:2021-11-07 07:10:34
【问题描述】:

我有这个 df

data.frame(Name = c("AI147", "AI147", "AI147", "AI147", "AI147", 
                         "AI20", "AI20", "AI87", "AI88", "AI88", "AI88", "AI65", "AI65"),
                         Presence1 = c("both_type1", "soil", "soil", "water", "both_type2", 
                         "soil", "water", "both_type2", "soil", "soil", "soil", "water", 
                         "water"))

我想根据每个名称的数据创建一个条件列(最终)。 (1) 如果给定名称具有多于 1 种存在类型,或仅存在“both_type1”或“both_type2”,则最终 = 两者,(2) 如果给定名称仅存在“土壤”​​,则最终 = 土壤, (3) 如果给定的 Name 仅存在“water”,则 Final = water,因此表格看起来像这样

data.frame(Name = c("AI147", "AI147", "AI147", "AI147", "AI147", 
                         "AI20", "AI20", "AI87", "AI88", "AI88", "AI88", "AI65", "AI65"),
                         Presence1 = c("both_type1", "soil", "soil", "water", "both_type2", 
                         "soil", "water", "both_type2", "soil", "soil", "soil", "water", 
                         "water"),
                         Final = c("both", "both", "both", "both", "both", "both", 
                         "both", "both", "soil", "soil", "soil", "water", "water"))

我已经尝试了几种我在网站上找到的方法,但没有一种方法能做到这一点。

【问题讨论】:

    标签: r multiple-conditions


    【解决方案1】:

    我们可以使用n_distinct 或使用str_detect 创建条件,即如果“Presence1”包含any“both”子字符串或具有多个唯一值(n_distinct),则在按“名称”分组后,然后return 'both' 否则返回 'Presence1' 的值

    library(dplyr)
    library(stringr)
    df1 <- df %>%
        group_by(Name) %>% 
        mutate(Final = case_when(any(str_detect(Presence1, 
           "both")|n_distinct(Presence1) > 1) ~ 'both',
            TRUE ~ Presence1 )) %>%
        ungroup
    

    -输出

    df1
    # A tibble: 13 x 3
       Name  Presence1  Final
       <chr> <chr>      <chr>
     1 AI147 both_type1 both 
     2 AI147 soil       both 
     3 AI147 soil       both 
     4 AI147 water      both 
     5 AI147 both_type2 both 
     6 AI20  soil       both 
     7 AI20  water      both 
     8 AI87  both_type2 both 
     9 AI88  soil       soil 
    10 AI88  soil       soil 
    11 AI88  soil       soil 
    12 AI65  water      water
    13 AI65  water      water
    

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2018-09-08
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多