检测短语含特定词汇及用mutate函数生成性别标识列的方法
Got it, let's break down these two R tasks step by step—they’re both easy to implement with the right functions!
To check if a single phrase or a vector of phrases contains a specific term, R’s grepl() function is your go-to tool. It returns a logical value (TRUE/FALSE) indicating whether the target term exists in each input string.
Example usage:
# Check a single phrase single_phrase <- "Good day, Mr. Anderson" grepl("Mr\\.", single_phrase) # Returns TRUE—note we escape the dot (\\.) because it's a special regex character # Check a vector of phrases phrase_vector <- c("Mr. Carter", "Ms. Davis", "Dr. Evans", "Mr. Foster") grepl("Mr\\.", phrase_vector) # Returns [TRUE, FALSE, FALSE, TRUE]
If you don’t need regex matching (just an exact string match), use the fixed=TRUE parameter to avoid escaping special characters:
grepl("Mr.", single_phrase, fixed=TRUE) # Also returns TRUE
Assuming you have a data frame (let’s call it name_dataset) with a column of names (e.g., full_name), we’ll use dplyr’s mutate() function to create a new column (say, gender) where entries are "Male" whenever the name includes "Mr.".
First, make sure you’ve loaded the dplyr package, then run this code:
library(dplyr) # Update the data frame with the new column name_dataset <- name_dataset %>% mutate(gender = ifelse(grepl("Mr\\.", full_name), "Male", NA))
Quick breakdown of the code:
grepl("Mr\\.", full_name): Checks each row’sfull_namefor "Mr." and returns a logical vectorifelse(): Assigns "Male" to rows where the check isTRUE, andNAto others- For more flexibility (e.g., handling "Ms." or "Mrs." too), use
case_when()instead—it’s cleaner for multiple conditions:
name_dataset <- name_dataset %>% mutate(gender = case_when( grepl("Mr\\.", full_name) ~ "Male", grepl("Ms\\.|Mrs\\.", full_name) ~ "Female", TRUE ~ NA_character_ # Catch-all for other cases ))
内容的提问来源于stack exchange,提问作者Carlo Montesa Espiritu

