Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing variable output name in glm

I have built a function f that runs an anova given an x and y variable. I used NSE to make the function easier to use. Here is an example that is replicable and isolates the problem:

library(carData)

df <- carData::Salaries


f <- function(x,y, data){
  x <- ensym(x)
  y <- ensym(y)
  m <- aov(glm(data[[y]] ~  data[[x]], family='gaussian',data=data))
  print(summary(m))
}

output:

> f(rank, salary, df )
             Df    Sum Sq   Mean Sq F value Pr(>F)    
data[[x]]     2 1.432e+11 7.162e+10   128.2 <2e-16 ***
Residuals   394 2.201e+11 5.586e+08                   
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

The function works, great! But the output shows the variable name as data[[x]]. I would like to change this variable name that matches the input.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have converted x to a character like:

x_string <- as.character(x)

But I don’t know where in glm I can change the variable name.

Thanks for any advice!

>Solution :

You could shorten your user defined function a bit and use substitute(y ~ x):

f <- function(x, y, data){
  m <- aov(glm(substitute(y ~  x), family = 'gaussian', data = data))
  summary(m)
}

f(rank, salary, df)

#              Df    Sum Sq   Mean Sq F value Pr(>F)    
# rank          2 1.432e+11 7.162e+10   128.2 <2e-16 ***
# Residuals   394 2.201e+11 5.586e+08                   
# ---
# Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading