如何通过ifelse模式匹配为R语言DataFrame生成指定编码的新列
R 实现DataFrame条件编码的ifelse方案
核心实现
你可以通过嵌套ifelse结合grepl正则匹配实现需求,代码如下:
df$code <- ifelse( grepl(pattern = "sun", x = df$condition), 1, ifelse( grepl(pattern = "dark|night", x = df$condition), 2, 99 ) )
参数说明
grepl是R中用于正则匹配的函数,匹配成功返回TRUE,失败返回FALSE,空值NA匹配会返回NA,最终会被归类到最后一个分支赋值99,完全符合需求- 正则表达式里的
|代表或逻辑,dark|night即匹配包含dark或者night的字符串 - 如果你需要不区分大小写匹配(比如同时识别
Sunny和sunny),可以在grepl中添加参数ignore.case = TRUE
效果验证
你可以用以下测试代码验证结果是否符合预期:
# 构造测试数据 df <- data.frame( condition = c("sunny", "sunshine", "dark", "night", "cloudy", NA, "rain") ) # 执行编码 df$code <- ifelse( grepl("sun", df$condition), 1, ifelse( grepl("dark|night", df$condition), 2, 99 ) ) # 输出结果 print(df)
运行后输出结果如下:
condition code 1 sunny 1 2 sunshine 1 3 dark 2 4 night 2 5 cloudy 99 6 <NA> 99 7 rain 99
内容的提问来源于stack exchange,提问作者Henrik
相关产品推荐
相关产品推荐

