Change name of input variable in a function

Hi R community,

I have made a function and I would like the input name to be changed in my output.

So, this is my function:

logReg_fun <- function(predictor){      
  reg <- polr(formula = as.ordered(MTA_numeric) ~ predictor, data = sub_star, Hess = T);
  #OR, CI and p-value
  OR <- round(exp(reg$coefficients),digits = 2)
  CI <- round(exp(confint(reg)),digits = 2)
  ctable <- coef(summary(reg))
  p <- pnorm(abs(ctable[, "t value"]),lower.tail = F)*2
  ctable <- cbind(ctable,"p value" = p); round(ctable,digits = 3) 
  #output
  print(reg)
  cbind("Odds ratio" = OR,"CI" = CI,"p value" = round(p[1:5],digits=3))
}

When running this I get a result where the output is called predictor:

          Odds ratio   CI p value
predictor       0.93 0.75   0.519
0|0.25          0.93 1.15   0.000
0.25|0.5        0.93 0.75   0.000
0.5|0.75        0.93 1.15   0.988
0.75|1          0.93 0.75   0.754

However, I would like to add something to my function such that I can make the correct name of the predictor. I am going to make the function go into a for loop such that I can loop though different predictors, and thus I would like to keep track of the predictors in the output.

Thank you in advance!

Best,
Charlie

library rlang; has useful functionality for non-standard evaluation (NSE) and metaprogramming; but here is a base R approach to letting you set a data.frame column name to an arbitrary value whether you give it as a qouted string or unqouted (NSE).

give_me_1_to_5_as_column_with_name_x <- function(x){
   sx <- substitute(x)

  df1 <- data.frame(
     val = 1:5
  )
  names(df1) <- as.character(sx)
  df1
}
give_me_1_to_5_as_column_with_name_x("this_works")
# also
give_me_1_to_5_as_column_with_name_x(this_works)

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.