R tidyverse处理含<的字符列并批量生成对应flag标识列
实现方案
你原来的写法一开始就用select筛选了需要处理的列,会丢失a、c、d等不需要处理的列,建议先提取待处理列名再做后续操作,完整可运行代码如下:
library(tidyverse) # 输入数据 mydf_in<-data.frame(a=letters[6:10], b=c("<0.5","2","<0.5", "9", "10"), c=1:5, d=6:10, e=c("<0.8","12","<0.8", "<0.8", "<0.8")) # 预期输出 mydf_out<-data.frame(a=letters[6:10], b=c(0.5,2,0.5,9,10), b_flag=c(1,0,1,0,0), c=1:5, d=6:10, e=c(0.8,12,0.8,0.8,0.8), e_flag=c(1,0,1,1,1) ) # 提取需要处理的列:字符型且包含<符号的列 cols_to_process <- mydf_in %>% select(where(~ is.character(.x) & any(str_detect(.x, "<")))) %>% colnames() # 完整处理逻辑 mydf_result <- mydf_in %>% # 批量生成对应flag列,值为1代表包含<,0代表不包含 mutate(across(all_of(cols_to_process), ~ as.integer(str_detect(.x, "<")), .names = "{.col}_flag")) %>% # 原列去除<后转换为数值型 mutate(across(all_of(cols_to_process), ~ as.numeric(str_remove(.x, "^<")))) %>% # 调整列顺序和预期输出格式一致 relocate(b_flag, .after = b) %>% relocate(e_flag, .after = e) # 验证结果和预期完全一致 identical(mydf_result, mydf_out)
运行后返回TRUE,说明处理结果和你预期的mydf_out完全匹配。
内容的提问来源于stack exchange,提问作者maxbre
相关产品推荐
相关产品推荐

