在R语言中基于指定列多条件创建新变量的技术问询
解决方法:基于指定列创建标记变量
我们需要给数据框新增一个变量,规则是:只要第5至10列中任意一列包含C71.2、C75.1或G45.1这三个代码之一,新变量就赋值为1,否则为0。以下是两种实现方式:
方法一:Base R 实现
# 加载数据集 df <- structure(list(Participant.ID = c(1000171L, 1000368L, 1000370L, 1000414L, 1000672L, 1000726L, 1000921L, 1001044L, 1001141L, 1001366L ), MET.minutes.per.week.for.vigorous.activity...Instance.0 = c(0L, NA, 720L, 0L, 800L, NA, NA, 0L, 0L, NA), MET.minutes.per.week.for.moderate.activity...Instance.0 = c(0L, NA, 720L, 0L, 420L, NA, NA, 0L, 40L, NA), Summed.MET.minutes.per.week.for.all.activity...Instance.0 = c(132, NA, 2595, 99, 1880, NA, NA, 0, 106, NA), Operative.procedures...OPCS4 = c("[\"C71.2 Phacoemulsification of lens\"", "[\"E36.9 Unspecified diagnostic endoscopic examination of larynx\"", "[\"A52.1 Therapeutic lumbar epidural injection\"", "[\"O29.1 Subacromial decompression\"", "[\"W31.9 Unspecified other autograft of bone\"", "[\"G45.1 Fibreoptic endoscopic examination of upper gastrointestinal tract and biopsy of lesion of upper gastrointestinal tract\"", "[\"C71.2 Phacoemulsification of lens\"", "[\"E49.9 Unspecified diagnostic fibreoptic endoscopic examination of lower respiratory tract\"", "[\"A38.1 Extirpation of lesion of meninges of cortex of brain\"", "[\"G15.7 Fibreoptic endoscopic insertion of expanding covered metal stent into oesophagus\"" ), X = c("C75.1 Insertion of prosthetic replacement for lens NEC", "E49.2 Diagnostic fibreoptic endoscopic examination of lower respiratory tract and lavage of lesion of lower respiratory tract", "A57.7 Injection of therapeutic substance around spinal nerve root", "S06.5 Excision of lesion of skin of head or neck NEC", "W37.1 Primary total prosthetic replacement of hip joint using cement", "H15.4 Closure of colostomy", "C75.1 Insertion of prosthetic replacement for lens NEC", "G45.1 Fibreoptic endoscopic examination of upper gastrointestinal tract and biopsy of lesion of upper gastrointestinal tract", "U05.1 Computed tomography of head", "G16.2 Diagnostic fibreoptic endoscopic ultrasound examination of oesophagus" ), X.1 = c("C86.5 Fluorescein angiography of eye", "F36.2 Biopsy of lesion of tonsil", "A60.4 Radiofrequency controlled thermal destruction of peripheral nerve", "S27.5 Local flap of skin to head or neck NEC", "X50.1 Direct current cardioversion", "H15.9 Unspecified other exteriorisation of colon", "C79.2 Vitrectomy using pars plana approach", "H22.1 Diagnostic fibreoptic endoscopic examination of colon and biopsy of lesion of colon", "U05.2 Magnetic resonance imaging of head", "G45.1 Fibreoptic endoscopic examination of upper gastrointestinal tract and biopsy of lesion of upper gastrointestinal tract" ), X.2 = c("C90.1 Topical anaesthetic", "K62.2 Percutaneous transluminal ablation of atrial wall for atrial flutter", "A73.5 Injection of therapeutic substance around peripheral nerve", "T62.2 Excision of bursa NEC", "X99.8 No procedure performed", "H22.9 Unspecified diagnostic endoscopic examination of colon", "C79.5 Internal tamponade of retina using gas", "N11.3 Eversion of hydrocele sac", "X99.8 No procedure performed", "J18.3 Total cholecystectomy NEC" ), X.3 = c("G45.1 Fibreoptic endoscopic examination of upper gastrointestinal tract and biopsy of lesion of upper gastrointestinal tract", "U05.1 Computed tomography of head", "E59.1 Needle biopsy of lesion of lung", "T65.2 Excision of lesion of tendon", "Y66.8 Other specified harvest of bone", "H33.5 Rectosigmoidectomy and closure of rectal stump and exteriorisation of bowel", "C80.1 Peel of epiretinal fibroglial membrane", "U13.6 Computed tomography of bone", "Y46.2 Frontal open approach to contents of cranium", "J37.3 Direct puncture operative cholangiography" ), X.4 = c("G45.9 Unspecified diagnostic fibreoptic endoscopic examination of upper gastrointestinal tract", "U20.1 Transthoracic echocardiography", "G45.1 Fibreoptic endoscopic examination of upper gastrointestinal tract and biopsy of lesion of upper gastrointestinal tract", "W84.4 Endoscopic decompression of joint", "Z75.6 Acetabulum", "S35.2 Meshed split autograft of skin NEC", "C80.2 Peel of internal limiting membrane", "U33.1 Polysomnography", "Y53.8 Other specified approach to organ under image control", "J43.9 Unspecified diagnostic endoscopic retrograde examination of bile duct and pancreatic duct" )), row.names = c(NA, 10L), class = "data.frame") # 定义需要匹配的目标代码 target_codes <- c("C71.2", "C75.1", "G45.1") # 逐行检查第5-10列是否存在目标代码 df$has_target_code <- apply(df[,5:10], 1, function(row) { any(sapply(target_codes, function(code) grepl(code, row))) }) # 将逻辑值转为0/1格式 df$has_target_code <- as.integer(df$has_target_code)
方法二:Tidyverse 实现
如果你习惯用tidyverse工具链,代码会更简洁:
library(dplyr) library(stringr) # 加载数据集(同上,省略重复代码) # 新增标记变量 df <- df %>% rowwise() %>% mutate(has_target_code = as.integer(any(str_detect(c_across(5:10), paste(target_codes, collapse = "|"))))) %>% ungroup()
补充说明
两种方法都会自动识别单元格字符串中包含的目标代码——因为你的数据里代码后面跟着描述文本,直接用字符串匹配就足够,不需要额外提取代码部分。
内容的提问来源于stack exchange,提问作者MaxB
相关产品推荐
相关产品推荐

