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

How to get the object name as a string inside a function in r

I want to change column names of a data frame with a function.

To overwrite my data frame with the new column names, I used assign(), which first argument has to be the name of the same data frame as a string. To get the name as a string, I used deparse(substitute(x)), which worked outside the function. But inside the function, it returns the content of my data frame as a string instead of the name itself…


df <- data.frame(
  emp_id = c (1:5), 
  emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
  stringsAsFactors = FALSE
)

deparse(substitute(df))

rename_fun <- function(x) {
  colnames(x)[1] <- "___0"
  colnames(x)[2] <- "___1"

  y <- deparse(substitute(x))
  
    assign(y, x, envir = .GlobalEnv)      
}

rename_fun(df)

I also tried

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

as.character(substitute(x))

but the same problem…

Thanks for any help!

>Solution :

We need to use deparse/substitute at the start of the function

rename_fun <- function(x) {
 y <- deparse(substitute(x))
  colnames(x)[1] <- "___0"
  colnames(x)[2] <- "___1" 
  
  assign(y, x, envir = .GlobalEnv)      
}

-testing

> rename_fun(df)
> df
  ___0     ___1
1    1     Rick
2    2      Dan
3    3 Michelle
4    4     Ryan
5    5     Gary
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