【问题标题】:How to extract rows that contain certain string in any column如何在任何列中提取包含特定字符串的行
【发布时间】:2020-11-10 03:35:36
【问题描述】:

I am dealing with a data frame as shown in this image, but with 380 rows in total

不确定这是否会有所帮助,但假设我正在处理数据框:

df <- data.frame(c(-10:-1),c(-5:4),c(1:10))

我想提取第一列或第二列中包含数字“-5”的任何行。

在共享图像中,我想在“HomeTeam”或“AwayTeam”列中提取包含“Arsenal”的行,但我不知道该怎么做。

This is my attempt using grep()

但它显示以下消息:

"Error: Can't subset columns that don't exist. x The locations 12, 39, 45, 78, 98, etc. don't exist. i There are only 7 columns."

提到的位置正是我需要的行...

我想尝试其他一些过滤功能,例如 dplyr(),但我不明白它是如何工作的......而且我什至不确定它是否适合我想做的事情。

【问题讨论】:

  • 欢迎来到 Stack Overflow。请make this question reproducible 以纯文本格式包含代码和示例数据 - 例如来自dput(yourdata) 的输出。我们无法从图像中复制/粘贴数据。
  • 试试 League1819[grepl('Arsenal', League1819$HomeTeam)|grepl('Arsenal', League1819$AwayTeam), ]

标签: r dplyr


【解决方案1】:

使用您的df <- data.frame(c(-10:-1),c(-5:4),c(1:10)) 示例,并且由于您(可能)已经在使用tidyverse,因此可以使用代码实现您想要的:

if(!require(tidyverse)) install.packages('tidyverse'); library(tidyverse) #to load the package, just in case you haven't already!
df <- data.frame(c(-10:-1),c(-5:4),c(1:10))
colnames(df) <- c("col1", "col2", "col3")
df %>% filter(col1 %in% "-5" | col2 %in% "-5")

或者如果您希望两列中都包含 -5 的行,您可以使用:

df %>% filter(col1 %in% "-5" & col2 %in% "-5")

相反。对于您的联赛问题,我会这样做:

sample_Arsenal <- league1819 %>% filter(HomeTeam %in% "Arsenal" | AwayTeam %in% "Arsenal")

【讨论】:

    【解决方案2】:

    你可以使用grepl

    sampleArsenal <- subset(league1819, grepl('Aresenal', HomeTeam) | 
                                        grepl('Aresenal', AwayTeam))
    

    或者如果你想试试dplyr

    library(dplyr)
    library(stringr)
    
    league1819 %>% 
       filter(str_detect(HomeTeam, 'Aresenal') | str_detect(AwayTeam, 'Aresenal'))
    

    【讨论】:

    • 天哪,这工作得很好。非常感谢先生!很抱歉以不可重复的方式提出问题,因为我对 R 非常陌生......并且不确定如何生成类似的案例。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-11-16
    • 2021-12-26
    • 1970-01-01
    • 2015-01-20
    • 2021-11-28
    • 2017-08-02
    • 2018-02-25
    • 1970-01-01
    相关资源
    最近更新 更多