Search code examples
rdataframedput

How to directly open .R data containing data frame code in R?


Here is an dataset

Environment= c("ENV1","ENV2","ENV3","ENV4","ENV5")
CV1<- c(25.2,26.3,15.2,22.1,21.9)
CV2<- c(37.1,34.5,26.0,29.9,28.3)
CV3<- c(33.0,30.5,25.0,30.2,28.9)
CV4<- c(35.4,37.0,28.0,26.0,34.0)
CV5<- c(34.6,32.7,20.0,32.3,28.6)

dataA= data.frame(Environment,CV1,CV2,CV3,CV4,CV5)

and I want to convert this data table as data frame code

dput(dataA)

structure(list(Environment = c("ENV1", "ENV2", "ENV3", "ENV4", 
                               "ENV5"), CV1 = c(25.2, 26.3, 15.2, 22.1, 21.9), 
               CV2 = c(37.1, 34.5, 26, 29.9, 28.3), 
               CV3 = c(33, 30.5, 25, 30.2, 28.9), 
               CV4 = c(35.4, 37, 28, 26, 34), 
               CV5 = c(34.6, 32.7, 20, 32.3, 28.6)), 
              class = "data.frame", row.names = c(NA, -5L))

Then, I saved this code as .R data for some cases. I saved as data_code.R in my PC.

enter image description here

Later, I want to open this data again, but directly want to open it as data table. For example, I want like

df= C:/Users/Desktop/data_code.R

print(df)
  Environment  CV1  CV2  CV3  CV4  CV5
1        ENV1 25.2 37.1 33.0 35.4 34.6
2        ENV2 26.3 34.5 30.5 37.0 32.7
3        ENV3 15.2 26.0 25.0 28.0 20.0
4        ENV4 22.1 29.9 30.2 26.0 32.3
5        ENV5 21.9 28.3 28.9 34.0 28.6

Is that possible to import data frame code to directly R?

Thanks,


Solution

  • Here are a few ways. A few more ways (fread/fwrite, RDS, feather, fst) can be found here.

    # 1
    dput(dataA, "dataA.R")
    dataB <- dget("dataA.R")
    identical(dataA, dataB)
    ## [1] TRUE
    
    # 2
    save(dataA, file = "dataA.Rdata")
    load("dataA.Rdata", envir = e <- new.env())
    identical(dataA, e$dataA)
    ## [1] TRUE
    
    # 3
    write.csv(dataA, "dataA.csv", row.names = FALSE)
    dataB <- read.csv("dataA.csv")
    identical(dataA, dataB)
    ## [1] TRUE
    
    # 4
    library(arrow)
    write_parquet(dataA, normalizePath("dataA.parquet", mustWork = FALSE))
    dataB <- read_parquet("dataA_parquet") |> as.data.frame()
    identical(dataA, dataB)
    ## [1] TRUE
    
    # 5
    library(writexl)
    library(readxl)
    write_xlsx(dataA, "dataA.xlsx")
    dataB <- read_xlsx("dataA.xlsx") |> as.data.frame()
    identical(dataA, dataB)
    ## [1] TRUE
    
    # 6
    library(RSQLite)
    con <- dbConnect(SQLite(), "dataA.sqlite")
    dbWriteTable(con, "dataA", dataA)
    dbDisconnect(con)
    con <- dbConnect(SQLite(), "dataA.sqlite")
    dataB <- dbReadTable(con, "dataA")
    identical(dataA, dataB)
    ## [1] TRUE