You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

检测短语含特定词汇及用mutate函数生成性别标识列的方法

Got it, let's break down these two R tasks step by step—they’re both easy to implement with the right functions!

1. 检测指定短语是否包含特定词汇

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
2. 使用mutate新增基于姓名的性别列

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’s full_name for "Mr." and returns a logical vector
  • ifelse(): Assigns "Male" to rows where the check is TRUE, and NA to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:11:34