【问题标题】:Subsetting strings from a column if they match multiple strings in a different column如果字符串与不同列中的多个字符串匹配,则从列中子集字符串
【发布时间】:2021-04-30 16:35:14
【问题描述】:

我有一个数据框,我想在其中对列进行子集化,以仅包含与不同列中的多个字符串匹配的字符串。这是一些模拟数据:

df1 <- data.frame(species = c("Rufl","Rufl","Soca","Assp","Assp","Elre"),
                  state = c("warmed","ambient","warmed","warmed","ambient","ambient"))

我想要一个数据框,其中仅包含与“温暖”和“环境”状态匹配的物种,删除仅匹配一个字符串的物种,因此最终数据框将具有“Rufl”和“Assp”及其给定状态,如下图

species  state
Rufl     warmed
Rufl     ambient
Assp     warmed
Assp     ambient

我已经尝试了一些不同的尝试,包括子集函数和 dplyr,但无法找到正确的方法来让它工作。这是我失败的尝试:

df2 <- subset(df1$species, state == "warmed" & state == "ambient")

# or this?
df2 <- df1 %>%
        group_by(species) %>%
        filter(state == "warmed",
               state == "ambient")

感谢您的帮助!

使用 R 版本 4.0.2,Mac OS X 10.13.6

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    我们需要all的群组

    library(dplyr)
    df1 %>%
       group_by(species) %>% 
       filter(all(c('warmed', 'ambient') %in% state)) %>%
       ungroup
    

    -输出

    # A tibble: 4 x 2
    #  species state  
    #  <chr>   <chr>  
    #1 Rufl    warmed 
    #2 Rufl    ambient
    #3 Assp    warmed 
    #4 Assp    ambient
    

    &amp; 操作不起作用,因为元素不在同一位置


    或使用subset

    subset(df1, species %in% names(which(rowSums(table(df1) > 0) == 2)))
    

    【讨论】:

      【解决方案2】:

      另一个使用ave的基本R选项

      subset(
        df1,
        ave(state, species, FUN = function(x) sum(c("warmed", "ambient") %in% x)) == 2
      )
      

      给予

        species   state
      1    Rufl  warmed
      2    Rufl ambient
      4    Assp  warmed
      5    Assp ambient
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-28
        • 2020-11-11
        • 1970-01-01
        • 1970-01-01
        • 2013-06-18
        • 2020-09-20
        • 2019-06-26
        • 1970-01-01
        相关资源
        最近更新 更多