You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于条件创建新数值变量:首次访视体重变量构建遇逻辑问题

How to Capture First Visit Weight for All Patient Rows

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:

SidWeight_KGvisitnumBMIFirst_Visit_Weight
A100113100
B500225NA
C7012070
D9011890
E82127NA

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:09:21