OrangePeel
OrangePeel

Reputation: 41

How to rename dataframe in R?

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.

Upvotes: 1

Views: 2333

Answers (2)

Konrad
Konrad

Reputation: 18585

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

library("gdata")
dfA <- data.frame(colA = c(1,2), colB = c(3,4))
ls()
# [1] "dfA"
# to: argument takes any string so conveniently it can be used 
#     with usual string manipulation functions
mv(from = "dfA", to = paste0("df", "B"))
ls()
# "dfB"

Notes

  • Concerning your observation:

    PS: it seems difficult to pass parameters in R function

    That depends on the individual's perspective, R may be considered as easier or more challenging, depending on the developer's background, level of experience, etc. I reckon that's a subject for a longer conversation.

  • mv offered within the gdata, makes use of assign, similarly to the valid answer contributed by @Rui Barradas, plus provides some other gadgets for the argument checking and optional target environment. Whether it makes sense to rely on this package to accomplish this minor task is mostly a matter of taste/approach to handling dependencies.

Upvotes: 1

Rui Barradas
Rui Barradas

Reputation: 76470

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)

Upvotes: 1

Related Questions