Home > Mobile >  How to rename dataframe in R?
How to rename dataframe in R?

Time:03-23

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

CodePudding user response:

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)

CodePudding user response:

A potentially interesting alternative is to use the mv function fro the gdata package:

library("gdata")
dfA <- data.frame(colA = c(1,2), colB = c(3,4))
ls()
# [1] "dfA"
mv(from = "dfA", to = paste0("df", "B"))
ls()
# "dfB"

Notes

  • Related