【问题标题】:R Efficient way to update filesR 更新文件的有效方法
【发布时间】:2021-11-17 16:25:02
【问题描述】:

如果有,我想检查重复项(如果文件中已经存在记录),然后删除并再次写入,如果没有,则添加它。目前我正在将新信息更新到具有以下模式的文件:

library(dplyr)
library(purrr)
library(readr)

# CREATE FILE
fst <- tibble(id = 1,
       val = rnorm(1),
       val2 = rnorm(1))

readr::write_rds(fst, "example_file.rds")

create_data <- possibly(function(id = 1L){
  
  dt_out <- dplyr::tibble(id = id,
                   val = rnorm(1),
                   val2 = rnorm(1))
  
  out <- readr::read_rds("example_file.rds") %>% 
    bind_rows(dt_out) %>% 
    distinct(id, .keep_all = T)
  
  readr::write_rds(out, "example_file.rds")
  
}, otherwise = NA)

links <- c(1,1,2,3,2,3,4,5)

res <- purrr::map(links, ~create_data(.x))

read_rds("example_file.rds")
# A tibble: 5 x 3
     id    val   val2
  <dbl>  <dbl>  <dbl>
1     1  0.430  0.636
2     2 -0.348 -0.507
3     3  0.936 -0.343
4     4  0.871  1.59 
5     5 -1.06  -0.308

所以我有获取数据的功能,并在其中将新数据绑定到旧文件并检查重复项。我的想法是从每个函数运行中编写单个文件并在以后的阶段将它们组合起来。所以不要有一个大文件,而是1000个小文件。同样使用这种方法,我无法真正控制保留哪些记录实例,因为我认为 distinct 保留了第一条记录,我没有任何东西可以告诉我什么是第一条记录。

文件变得太大,当函数运行多次时,我没有足够的内存来来回读写它。是否有替代方法,我不需要读取整个文件并获得相同的结果,只有 1 个文件更新了新信息?

【问题讨论】:

  • 问题是什么?预期的结果是什么?
  • 我希望收到相同的结果,但不必读取和写入整个文件。这占用了太多内存,并且功能无法多次运行。尝试编辑问题以使其更简洁。

标签: r storage


【解决方案1】:

不完全是我想要的,因为我喜欢计算机中的文件并且没有使用过数据库,但这感觉很好。 MongoDB 可以处理我在数据中实际拥有的嵌套数据帧(因此是 .rds 格式)。安装 mongodb 还不错。

library(mongolite)

example_db <- mongo("example_db", url = "mongodb://127.0.0.1:27017/db_name")

fst <- tibble(id = 1,
              val = rnorm(1),
              val2 = rnorm(1))

example_db$insert(fst)

create_data <- purrr::possibly(function(id = 1L){
  
  dt_out <- dplyr::tibble(id = id,
                          val = rnorm(1),
                          val2 = rnorm(1))
  
  example_db$remove(paste0('{"id": {"$in":', jsonlite::toJSON(id), '} }'))
  example_db$insert(dt_out)
  
}, otherwise = NA)

links <- c(1,1,2,3,2,3,4,5)
res <- purrr::map(links, ~create_data(.x))

(example_db$find())
  id        val       val2
1  1  0.3772453 -0.4799636
2  2  0.3282423 -0.7768333
3  3 -1.1129543 -1.6095890
4  4 -0.9314038 -1.4073236
5  5  0.4243383 -1.0557676

当然数据现在不在文件中。这样我很确定只有最新的 ID 在 DB 中,因为它将被删除然后再次插入。同样使用$in,可以对其进行修改以一次处理多个ID。如果文件可以以类似的方式工作,那就太好了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多