[SOLVED] How to rename dataframe in R?

Issue

Suppose i have two data frames, dm and suppdm

test <- function(inds) {
    a1 <- inds
    a2 <- paste("supp", a1, sep = '')
    
    print(class(a1))
    print(class(a2))
}

test(dm)

At this time, a1 is the dm data frame, but a2 is not suppdm, just character. How to enter a parameter and use two data frames? Does this belong to the renaming of the data frame?


PS: it seems difficult to pass parameters in R function.

Solution

You must use assign to create an object with a name given by a character string and use get to get the object given by that string.
Note that the name with the prefix "supp" will only exist in the function and is discarded on exit.

test <- function(inds){
  a1 <- deparse(substitute(inds))
  a2 <- paste0("supp", a1)
  assign(a2, inds)
  out_df <- get(a2)
  
  print(class(a1))
  print(class(a2))
  print(class(out_df))
  
  out_df
}

head(test(iris))
#> [1] "character"
#> [1] "character"
#> [1] "data.frame"
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa

Created on 2022-03-23 by the reprex package (v2.0.1)

Answered By – Rui Barradas

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *