Home > database >  In R, how to copy object
In R, how to copy object

Time:01-13

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!

CodePudding user response:

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

  • Related