基于条件创建新数值变量:首次访视体重变量构建遇逻辑问题
It looks like your current function only returns the weight when the current row is visit 1, but doesn't carry that value over to other visits for the same patient. That's why it's not working as expected—we need to group by patient ID (Sid) and propagate the first visit weight across all their records.
First, let's fix your sample data frame to make it usable:
df <- structure( list( Sid = structure(1:5, .Label = c("A", "B", "C", "D", "E"), class = "factor"), Weight_KG = c(100L, 500L, 70L, 90L, 82L), visitnum = c(1L, 2L, 1L, 1L, 12L), BMI = c(13L, 25L, 20L, 18L, 7L) ), class = "data.frame", row.names = c(NA, -5L) )
Solution 1: Using dplyr (Cleanest Approach)
We'll group by patient ID, then create a new column that pulls the weight from visit 1 for each group. If a patient doesn't have a visit 1, it will default to NA.
library(dplyr) df_with_first_weight <- df %>% group_by(Sid) %>% mutate(First_Visit_Weight = Weight_KG[visitnum == 1]) %>% ungroup()
Output:
| Sid | Weight_KG | visitnum | BMI | First_Visit_Weight |
|---|---|---|---|---|
| A | 100 | 1 | 13 | 100 |
| B | 500 | 2 | 25 | NA |
| C | 70 | 1 | 20 | 70 |
| D | 90 | 1 | 18 | 90 |
| E | 82 | 12 | 7 | NA |
If you want to handle patients with multiple visit 1 rows (though this is likely a data error), you can use first() to pick the first occurrence:
mutate(First_Visit_Weight = first(Weight_KG[visitnum == 1]))
Solution 2: Base R (No External Libraries)
Using ave() to group by Sid and apply a custom function:
df$First_Visit_Weight <- ave( df$Weight_KG, df$Sid, FUN = function(w) { # Get weight where visitnum is 1 for this patient visit1_w <- df$Weight_KG[df$Sid == unique(df$Sid) & df$visitnum == 1] # Return the weight if exists, else NA if (length(visit1_w) > 0) visit1_w else NA } )
Why Your Original Function Didn't Work
Your function WL_A operates row-by-row: it only returns the weight if the current row's visitnum is 1, otherwise it returns NULL (which becomes NA). It doesn't look at other rows for the same patient. To get the first visit weight across all visits, we need to group by patient and retrieve the value from their visit 1 record, then assign it to all their rows.
内容的提问来源于stack exchange,提问作者Ava Wilson

