如何判断数据集月份变量组是否匹配随访月份变量并生成状态新变量
数据集处理需求说明
我处理的数据集每行对应1名受试者,需检索Jan至Jul共7个月份变量,判断是否存在与Follow-up month(随访月份)变量值匹配的记录,最终生成Follow_up_Status新变量,匹配赋值Yes,不匹配赋值No。
示例原始数据集(HAVE)
| ID | Jan | Feb | Mar | Apr | May | June | Jul | Follow-up month |
|---|---|---|---|---|---|---|---|---|
| 1 | NA | 2 | 3 | 4 | NA | NA | NA | 4 |
| 2 | NA | NA | NA | 4 | NA | NA | NA | 6 |
| 3 | 1 | NA | 3 | 4 | 5 | NA | NA | 5 |
| 4 | NA | NA | NA | NA | NA | 6 | 7 | 9 |
期望输出数据集(WANT)
| ID | Jan | Feb | Mar | Apr | May | June | Jul | Follow-up month | Follow_up_Status |
|---|---|---|---|---|---|---|---|---|---|
| 1 | NA | 2 | 3 | 4 | NA | NA | NA | 4 | Yes |
| 2 | NA | NA | NA | 4 | NA | NA | NA | 6 | No |
| 3 | 1 | NA | 3 | 4 | 5 | NA | NA | 5 | Yes |
| 4 | NA | NA | NA | NA | NA | 6 | 7 | 9 | No |
不同工具实现代码
R(tidyverse)
library(tidyverse) want <- have %>% mutate( # 判断Jan到Jul列中是否有值等于随访月份 Follow_up_Status = if_any(Jan:Jul, ~ .x == `Follow-up month`), # 逻辑值转为Yes/No Follow_up_Status = ifelse(Follow_up_Status, "Yes", "No") )
Python(pandas)
import pandas as pd import numpy as np month_cols = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Jul'] want = have.copy() # 逐行判断月份列中是否存在匹配值 want['Follow_up_Status'] = np.where( want[month_cols].eq(want['Follow-up month'], axis=0).any(axis=1), 'Yes', 'No' )
SAS
data want; set have; /* 定义月份数组 */ array months[*] Jan Feb Mar Apr May June Jul; Follow_up_Status = 'No'; do i = 1 to dim(months); if months[i] = `Follow-up month` then do; Follow_up_Status = 'Yes'; leave; /* 匹配到就跳出循环,提高效率 */ end; end; drop i; run;
内容的提问来源于stack exchange,提问作者Sophia
相关产品推荐
相关产品推荐

