【问题标题】:How to read a csv only for the first time running the script?如何仅在第一次运行脚本时读取 csv?
【发布时间】:2018-02-21 03:48:52
【问题描述】:

我的代码:

if (data == null) {
   data <- read.csv(file)
}

从大数据文件中读取,因此最好只读取一次。

【问题讨论】:

  • 你需要is.null,如果是大数据,试试fread,即library(data.table); fread(file)
  • 谢谢!我尝试使用 fread,但遇到了错误。
  • fread("temp_prec_small.csv.bz2", stringsAsFactors = FALSE) 中的错误:在字符串中嵌入 nul:'\xe7w\xd73\xb0(\x96\x8f\x92'Ȋj\xeb\xd1 \xd0&\x82\017\xcdx\xb8\xa3\x9aE\v\x86\xf0\xab\036\xadE\0320\xca#=\xceN\xfb\xca2Oc\xabĒj\x9c!\xc4A\0©"\ 017&\xc55\xe4\xd3\xd2\035\0210\xa2\n\t\002\021K]\xc8\031,\026)\001
  • 你说它是一个csv文件,但以你的错误信息结尾的文件是。 bz2
  • 从数据文件中找出您需要的内容并将其保存在一个更小的文件中,以便更快地读取。或者,如果您需要整个文件,请使用saveRDS/readRDS 将其保存为压缩二进制格式,该格式应小于原始文本。

标签: r rstudio


【解决方案1】:

您可以使用 exists(),但您还应该确保您使用的数据集名称可能不会被 R分配给您正在加载的数据。

不过,您可以通过以下方式处理它:

ls() ## I'm starting with nothing in my workspace
# character(0)

## Here's how you can check if something exists
if (!(exists("data") & is.data.frame(data))) {
  ## Replace print("boo") with whatever you actually want to do--
  ## Read data, load data, whatever
  print("boo")
} else {
  ## If it does exist, you don't really need to do anything
  ## Except proceed with your script
  head(data)
}
# [1] "boo"

如果我们的环境中有 data.frame 会发生以下情况(就像您已经读过一样)。

data <- data.frame(V1 = 1:10, V2 = 11:20)

ls()
# [1] "data"

if (!(exists("data") & is.data.frame(data))) {
  print("boo")
} else {
  head(data)
}
#   V1 V2
# 1  1 11
# 2  2 12
# 3  3 13
# 4  4 14
# 5  5 15
# 6  6 16

不过,正如其他人所提到的,您也可以考虑将数据保存为可以快速加载的“rdata”或“rds”格式。

【讨论】:

    【解决方案2】:

    您可以检查数据是否已经具有某些属性(例如类)或是否存在。第一个解决方案很简单,但在技术上并不正确;第二种解决方案有时会很棘手,具体取决于您的环境和变量名称

    ## Creating data
    test1 <- c(1:5, "6,7", "8,9,10")
    file <- tempfile()
    writeLines(test1, file)
    

    解决方案 1

    if (!exists("data")) {
       data <-read.csv(file)
    }
    

    解决方案 2

    ## Check an attribute (e.g. the class)
    check_class <- try(class(data), silent = TRUE)
    
    ## Check if the data existed (i.e. had an attribute or not)
    if (class(check_class) == "try-error") {
       data1 <-read.csv(file)
    }
    

    【讨论】:

    • 由于某种原因,解决方案 1 不起作用。它似乎没有读取 csv 文件
    • Nvm,我认为这是 b/c 我正在检查“数据”是否存在。谢谢!
    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 2011-07-29
    • 2019-02-10
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多