Home > database >  Is there a way to incorporate an existing object name as part of a new object name in R?
Is there a way to incorporate an existing object name as part of a new object name in R?

Time:04-08

I have a function that takes a data frame 'my_df' as input and creates a new data frame as output. I would like the function to assign the name 'my_df_updated'to the new data frame. That is, keep 'my_df' as the generic argument to the function so that the assigned name will have whatever data frame is inputted 'updated' appended to it. For example, if my input data frame name is 'df1', the output data frame will be named, 'df1_updated'.

I tried to assign function output to paste(my_df, "_updated") but it gave an 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