Home > other >  Programmatically appending an existing object name to a new object name
Programmatically appending an existing object name to a new object name

Time:04-08

I have a function that takes a data frame as input and creates a new data frame as output.

I would like the function to assign a name of <oldname>_updated to this output data frame.

For example, if my input data frame name is df1, the output data frame should be named df1_updated.

I tried assigning my function output to paste(my_df, "_updated") but it returned this error: target of assignment expands to non-language object.

CodePudding user response:

It's possible to do such a thing in R using assign, but it is considered bad practice for a function to have side effects in the calling frame such as adding variables without specific assignment.

It would be better to do my_df_updated <- update_df(my_df)

With that caveat, you can do:

update_df <- function(df) {

  # Make a minor change in data frame for demonstration purposes
  df[1, 1] <- df[1, 1]   1
  
  # Assign result with new name to the calling environment
  assign(paste0(deparse(match.call()$df), "_updated"), df,
         envir = parent.frame())
}

So now if you have this data frame:

my_df <- data.frame(x = 1)

my_df
#>   x
#> 1 1

You can do

update_df(my_df)

my_df_updated
#>   x
#> 1 2

Created on 2022-04-07 by the reprex package (v2.0.1)

  • Related