在R语言中保存与重新加载list对象
Hey there! I totally get the frustration of putting in the work to build a custom list, only to struggle with saving and loading it while keeping it as a list (not a dataframe or anything else). Let's break down the correct usage of R's built-in functions to fix this for you.
Using save() and load()
This is the classic method, but it's easy to trip up on the details:
- Saving your list: If your list is named
my_custom_list, use this command to save it to a file. Thefileparameter is mandatory here, and we typically use.RDataor.rdaas the file extension:save(my_custom_list, file = "my_custom_list.RData") - Loading your list: To bring it back into your environment, just run the
load()function with the file path. Important note: the list will reappear under its original name (my_custom_listin this case) — you don't need to assign it to a variable directly:
You can confirm it's still a list withload("my_custom_list.RData")class(my_custom_list)— it should return"list".
Common Pitfall to Avoid
A frequent mistake is trying to assign the result of load() to a variable, like new_list <- load("my_custom_list.RData"). This won't give you the list — instead, new_list will just hold the filename as a character string. The actual list is loaded directly into your environment with its original name.
Using saveRDS() and readRDS() (More Flexible Option)
If you prefer to assign the loaded list to a custom variable name (instead of being stuck with the original name), this method is better. It's designed for single objects, which makes it perfect for your list:
- Saving your list: Use
saveRDS()with your list and a file path (we usually use.rdsas the extension here):saveRDS(my_custom_list, file = "my_custom_list.rds") - Loading your list: Now you can assign the loaded object to any variable name you want, and it will retain its list type:
loaded_list <- readRDS("my_custom_list.rds") class(loaded_list) # Returns "list"
Quick Example to Test It Out
Let's walk through a full example to make sure it clicks:
# Create a sample custom list my_custom_list <- list( numbers = 1:10, text = c("I built this list!", "It took time!"), small_df = iris[1:5, ] ) # Save with save() save(my_custom_list, file = "my_list.RData") # Clear environment to test loading rm(list = ls()) load("my_list.RData") print(class(my_custom_list)) # Output: "list" # Save with saveRDS() saveRDS(my_custom_list, file = "my_list.rds") # Clear environment again rm(list = ls()) loaded_list <- readRDS("my_list.rds") print(class(loaded_list)) # Output: "list"
Both methods will ensure your list stays a list when loaded — no unexpected type changes to dataframes or other structures.
内容的提问来源于stack exchange,提问作者Chris T.

