0

In R, how to quote object in code ? for example there is object 'df1' in RAM --dataframe

library(tidyverse)
df1 <- data.frame(dt=c(1:100))
df1_copy <- sym(paste0("df","1"))

df1_copy not the same as df1 ---- df1_copy is "symbol" and value is "mt1"。How to fix it, Thanks!

anderwyang
  • 1,801
  • 4
  • 18
  • `df1_copy <- df1`? – Paul Stafford Allen Jan 12 '23 at 10:03
  • Yes , this can work . but I have so many object in RAM , I want to using loop statement to write out them , the code just a samiliar question . Thanks! – anderwyang Jan 12 '23 at 10:06
  • 1
    I'm sure someone will answer your question with the correct syntax, but I suspect this is an [XY problem](https://xyproblem.info/). Why are you doing this? R is set up for you to keep collections of objects in lists (including data frames, which are both a special type of list and work well when stored in lists to which you apply functions). – SamR Jan 12 '23 at 10:09
  • Something like this? `df1_copy <- mget(ls(pattern = paste0("df","1")))` – Sotos Jan 12 '23 at 10:12

1 Answers1

3

If you want to programmatically make copies of objects in your environment, you can go along the lines of the second answer to this post.

df1 <- data.frame(v1 = 1:10)
df2 <- data.frame(V1 = 11:20)

original.objects <- ls(pattern="df[0-9]+")

for(i in 1:length(original.objects)){
  assign(paste0("copy_", original.objects[i]), eval(as.name(original.objects[i])))
}

ls()
#> [1] "copy_df1"         "copy_df2"         "df1"              "df2"             
#> [5] "i"                "original.objects"

print(list(df1, df2, copy_df1, copy_df2))
#> [[1]]
#>    v1
#> 1   1
#> 2   2
#> 3   3
#> 4   4
#> 5   5
#> 6   6
#> 7   7
#> 8   8
#> 9   9
#> 10 10
#> 
#> [[2]]
#>    V1
#> 1  11
#> 2  12
#> 3  13
#> 4  14
#> 5  15
#> 6  16
#> 7  17
#> 8  18
#> 9  19
#> 10 20
#> 
#> [[3]]
#>    v1
#> 1   1
#> 2   2
#> 3   3
#> 4   4
#> 5   5
#> 6   6
#> 7   7
#> 8   8
#> 9   9
#> 10 10
#> 
#> [[4]]
#>    V1
#> 1  11
#> 2  12
#> 3  13
#> 4  14
#> 5  15
#> 6  16
#> 7  17
#> 8  18
#> 9  19
#> 10 20

Created on 2023-01-12 with reprex v2.0.2

Claudio
  • 1,229
  • 6
  • 11