How to open an R data file in R window

后端 未结 2 1748
粉色の甜心
粉色の甜心 2021-01-24 06:58

I have some data in R that I intend to analyze. However, the file is not displaying the data. Instead, It is only showing a variable in the data. The following is the procedure

2条回答
  •  醉话见心
    2021-01-24 08:00

    There are two ways to save R objects, and you've got them mixed up. In the first way, you save() any collection of objects in an environment to a file. When you load() that file, those objects are re-created with their original names in your current environment. This is how R saves and resotres workspaces.

    The second way stores (serializes) a single R object into a file with the saveRDS() function, and recreates it in your environment with the readRDS() function. If you don't assign the results of readRDS(), it'll just print to your screen and drift away.

    Examples below:

    # Make a simple dataframe
    testdf <- data.frame(x = 1:10,
                         y = rnorm(10))
    
    # Save it out using the save() function
    savedir <- tempdir()
    savepath <- file.path(savedir, "saved.Rdata")
    save(testdf, file = savepath)
    
    # Delete it
    rm(testdf)
    
    # Load without assigning - and it's back in your environment
    load(savepath)
    testdf
    
    # But if you assign the results of load, you just get the name of the object
    wrong <- load(savepath)
    wrong
    
    
    # Compare with the RDS:
    rds_path <- file.path(savedir, "testdf.rds")
    saveRDS(testdf, file = rds_path)
    rm(testdf)
    testdf <- readRDS(file = rds_path)
    testdf
    

    Why the two different approaches? The save()-environment approach is good for creating a checkpoint of your entire environment that you can restore later - that's what R uses it for - but that's about it. It's too easy for such an environment to get cluttered, and if an object you load() has the same name as an object in your current environment, it will overwrite that object:

    testdf$z <- "blah"
    load(savepath)
    testdf  # testdf$z is gone
    

    The RDS method lets you assign the name on read, as you're looking to do here. It's a little more annoying to save multiple objects, sure, but you probably shouldn't be saving objects very often anyway - recreating objects from scratch is the best way to ensure that your R code does what you think it does.

提交回复
热议问题