如何从 r svydesign 包中保存加权数据?
How to save a weighted data from r svydesign package?
有没有办法保存加权后的数据,下次直接加载?我有一个大型调查数据集,并使用 R 的 survey
包。我使用 feather
包加载数据,但在应用 svydesign 时需要相当长的时间。这是一个可重现的例子:
df <- data.frame(col1 = rnorm(20, 0, 1), col2 = rnorm(20, 2, 2), w = rnorm(20, 1, .2))
df.w <- svydesign(id = ~1, data = df, weights = ~w)
我想保存 df.w 以供日后分析。有办法吗?
您可以使用 saveRDS
和 readRDS
来 save/read 单个 R
对象。
library(survey)
df <- data.frame(col1 = rnorm(20, 0, 1), col2 = rnorm(20, 2, 2), w = rnorm(20, 1, .2))
df.w <- svydesign(id = ~1, data = df, weights = ~w)
####### save to file ##########
storage_file <- tempfile()
#storage_file <- "mydesign.rds" ## uncomment here to use a local file
saveRDS(df.w, storage_file)
######## clear workspace #########
rm(df, df.w)
######### load the data ###########
df.w.loaded <- readRDS(storage_file)
df.w.loaded
## Independent Sampling design (with replacement)
## svydesign(id = ~1, data = df, weights = ~w)
######## delete storage file ######
file.remove(storage_file)
如果您想将多个对象保存在一个文件中,请查看 ?save
和 ?load
。
有没有办法保存加权后的数据,下次直接加载?我有一个大型调查数据集,并使用 R 的 survey
包。我使用 feather
包加载数据,但在应用 svydesign 时需要相当长的时间。这是一个可重现的例子:
df <- data.frame(col1 = rnorm(20, 0, 1), col2 = rnorm(20, 2, 2), w = rnorm(20, 1, .2))
df.w <- svydesign(id = ~1, data = df, weights = ~w)
我想保存 df.w 以供日后分析。有办法吗?
您可以使用 saveRDS
和 readRDS
来 save/read 单个 R
对象。
library(survey)
df <- data.frame(col1 = rnorm(20, 0, 1), col2 = rnorm(20, 2, 2), w = rnorm(20, 1, .2))
df.w <- svydesign(id = ~1, data = df, weights = ~w)
####### save to file ##########
storage_file <- tempfile()
#storage_file <- "mydesign.rds" ## uncomment here to use a local file
saveRDS(df.w, storage_file)
######## clear workspace #########
rm(df, df.w)
######### load the data ###########
df.w.loaded <- readRDS(storage_file)
df.w.loaded
## Independent Sampling design (with replacement)
## svydesign(id = ~1, data = df, weights = ~w)
######## delete storage file ######
file.remove(storage_file)
如果您想将多个对象保存在一个文件中,请查看 ?save
和 ?load
。