【问题标题】:How to save a weighted data from r svydesign package?如何从 r svydesign 包中保存加权数据?
【发布时间】:2023-03-05 04:37:01
【问题描述】:

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

【问题讨论】:

    标签: r survey


    【解决方案1】:

    您可以像这样使用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

    【讨论】:

    • 如果以后的读者看不出来,临时目录会在 R 关闭时被清除,所以即使 saveRDS() 是正确的答案,也不应该使用这个确切的代码。
    • 感谢格雷戈尔和托马斯。虽然使用 rds 格式更简单,但并没有提高加载时间。我比较了时序,发现 read_feather+svydesign 的运行速度比 saveRDS+loadRDS(或 readr 包中的 write_rds+read_rds)快得多;包括非压缩 rds。我错过了什么吗?
    • 嗨,saveRDS 参数compress = FALSE 需要更多磁盘空间,但提高了加载速度
    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 2022-11-07
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多