如何保存r svydesign包中的加权数据?

时间:2017-12-17 14:59:03

标签: r survey

有没有办法保存加权数据,以便下次我直接加载它?我有一个大型的调查数据集,并使用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 并将其用于将来的分析。有办法吗?

1 个答案:

答案 0 :(得分:3)

您可以使用saveRDSreadRDS来保存/阅读此类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