Combined data frame names & variable names within a function to create new variables

Is this what you mean?

# Sample data
sample_df <- data.frame(
          ID = c(1,2,3,4,5,6,7,8,9,10,11,12,13,
                 14,15,16,17,18,19),
           X = c(1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
           Y = c(0, NA, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1),
           Z = c(NA,NA,NA,NA,1,1,NA,NA,1,1,1,1,
                 NA,0,NA,NA,1,NA,0)
)

my_func <-  function(dat,var1,var2){
    dat[[var2]] <- ifelse(is.na(dat[[var1]]), NA, dat[[var2]])
    print(dat[[var2]])
}

my_func(sample_df, "Y", "Z")
#>  [1] NA NA NA NA  1  1 NA NA  1  1  1  1 NA  0 NA NA  1 NA  0

Created on 2021-12-02 by the reprex package (v2.0.1)

If this doesn't solve your problem, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

1 Like