1

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.

Andrea M
  • 2,314
  • 1
  • 9
  • 27
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. But generally this is a bad idea. Functions should return new values and the calling expression should save to an object if necessary. We try to avoid functions that modify variables outsider their scope because the side effects can be difficult to track and make code re-use much more difficult. Though it can be done with the `assign()` function. – MrFlick Apr 07 '22 at 18:18

1 Answers1

2

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)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87