如何使用dplyr的filter筛选含全大写字符串的数据行?
筛选包含全大写字符串的数据行(R语言dplyr实现)
首先定义你的数据框:
col1 <- c("Hello my NAME is", "How are YOU", "I'm doing well") col2 <- c("Thank YOU", "How are you doing?", "Life is HARD") col3 <- c("I'm sorry to hear", "That's how it GOES", "RIGHT") df <- data.frame(col1, col2, col3)
1. 筛选col1中包含全大写字符串的行
使用dplyr的filter结合stringr的str_detect,正则表达式[A-Z]+用于匹配一个或多个连续大写字母:
library(dplyr) library(stringr) df %>% filter(str_detect(col1, "[A-Z]+"))
运行后会保留原始数据的第1、2行。
2. 筛选col2中包含全大写字符串的行
针对col2执行相同逻辑的筛选:
df %>% filter(str_detect(col2, "[A-Z]+"))
运行后会保留原始数据的第1、3行。
3. 筛选col3中包含全大写字符串的行
针对col3执行筛选:
df %>% filter(str_detect(col3, "[A-Z]+"))
运行后会保留原始数据的第2、3行。
内容的提问来源于stack exchange,提问作者hy9fesh
相关产品推荐
相关产品推荐

