0

I am trying to create a new variable that consists of the patients weight in kg at the time of visit 1, but I am having trouble with the logic. I have tried the following code but have have no luck

WL_A <- function(visitnum, Weight_KG) {
  if (visitnum == 1)
    return(Weight_KG)
}

data

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)), .Names = c("Sid", "Weight_KG", "visitnum", "BMI"
), class = "data.frame", row.names = c("1", "2", "3", "4", "5"))
markus
  • 25,843
  • 5
  • 39
  • 58
Ava Wilson
  • 33
  • 5
  • 1
    And what's your question/problem? – pogibas May 01 '18 at 18:15
  • I am having trouble creating a new variable called WL_A that only includes the weight of patients (numeric) at visit 1. The function I wrote only returns T/F which isn't very helpful – Ava Wilson May 01 '18 at 18:19
  • 1
    Is there data behind this? What does it look like? What is its structure? How is your function to know about a patient (as you have it set up, it takes in a visit num and a weight, and if the visit is 1, it outputs the same weight it was input)? Maybe have a look at [How to make a reproducible example in R](https://stackoverflow.com/q/5963269/903061) for a nice walkthrough of how to ask a good *answerable* question. – Gregor Thomas May 01 '18 at 18:19
  • Cannot answer without reproducible example, but you likely want `library(dplyr); df %>% group_by(patientID) %>% mutate(first.weight = Weight_KG[visitnum == 1])` – IceCreamToucan May 01 '18 at 18:21
  • Ah sorry im so new this is how the data frame is structured Sid Weight_KG visitnum BMI 1 A 100 1 13 2 B 500 2 25 3 C 70 1 20 4 D 90 1 18 5 E 82 12 7 – Ava Wilson May 01 '18 at 18:27
  • Does this give you the desired result: `df$WL_A <- ifelse(df$visitnum == 1, df$Weight_KG, "")` ? The class of `df$WL_A` is character though. – markus May 01 '18 at 18:39
  • Thanks for the `dput`, that is very helpful. Could you also show your desired result? A new column added to your data? Or a separate data frame with just the first weights? If it's a new column, try Renu's code, replacing `patientID` with `Sid`. – Gregor Thomas May 01 '18 at 18:42
  • yes it did thank if you! – Ava Wilson May 01 '18 at 18:42
  • @markus use `NA` instead of `""` to keep it integer. – Gregor Thomas May 01 '18 at 18:46
  • @Gregor Thanks. You're right of course. Just wasn't sure about the expected output. – markus May 01 '18 at 18:53

0 Answers0