【问题标题】:R subsetting dataframe on partial string match or separating or splitR 对部分字符串匹配或分离或拆分的数据帧进行子集化
【发布时间】:2021-07-21 05:02:09
【问题描述】:

我正在尝试通过部分字符串匹配来子集数据帧。拆分和比较也可以工作,因为字符串可以用“|”拆分 我相信我在过去的类似案例中使用了 %in% ,但它对此不起作用。 有什么建议吗?

df <- read.table(text="
col1    cOL2      
1   '2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.1.47'
2   '2.16.840.1.113883.10.20.22.4.4 | 2.16.840.1.113883.10.20.22.4.4 | 2.16.840.1.113883.10.20.22.4.64'
3   '2.16.840.1.113883.10.20.22.4.64 | 2.16.840.1.113883.10.20.22.4.78 | 2.16.840.1.113883.10.20.1.47'
4    '2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.1.47'
5   '2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.1.47'
", header=T, stringsAsFactors=FALSE)
df[which(df$cOL2 == 1 & df$cOL2 %in% '2.16.840.1.113883.10.20.22.4.19' ),]

【问题讨论】:

    标签: r dataframe compare subset string-matching


    【解决方案1】:

    使用基本 R 函数,您可以:

    subset(df, grepl('2.16.840.1.113883.10.20.22.4.19', cOL2))
      col1                                                                                             cOL2
    1    1 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.1.47
    4    4 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.1.47
    5    5 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.1.47
    

    【讨论】:

    • 有没有办法使用 df[, ] 方式,我有很多具有多个过滤条件的子集,我可以,但我不一定想全部更改。谢谢
    • @Bristle 是的,这是基本的 R 代码。只需执行df[, grepl('2.16.840.1.113883.10.20.22.4.19', df$cOL2)]。你可以使用[]subset完全相同的方式
    • df[grepl('2.16.840.1.113883.10.20.22.4.19', df$cOL2),]
    【解决方案2】:

    一个整洁的选项。

    library(tidyverse)
    
    filter(df, str_detect(cOL2, '2.16.840.1.113883.10.20.22.4.19'))
    
    #      col1                                                                                             cOL2
    #    1    1 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.1.47
    #    2    4 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.1.47
    #    3    5 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.22.4.19 | 2.16.840.1.113883.10.20.1.47
    

    坚持[],您可以执行以下操作。

    library(tidyverse)
    
    df[str_detect(df$cOL2, '2.16.840.1.113883.10.20.22.4.19'),]
    

    【讨论】:

    • 有没有办法使用 df[, ] 方式,我有很多具有多个过滤条件的子集,我可以,但我不一定想全部更改。谢谢
    • @Bristle:我已经编辑了我的帖子以满足您的要求。
    • 啊!非常感谢!
    猜你喜欢
    • 2016-10-18
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 2022-01-17
    • 2015-05-18
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多