R 如何仅在第一次运行脚本时读取csv?
我的代码:R 如何仅在第一次运行脚本时读取csv?,r,rstudio,R,Rstudio,我的代码: if (data == null) { data <- read.csv(file) } if(数据==null){ 数据您可以使用exists(),但是您还应该确保为数据集使用的名称可能不是R所能找到的。data()是R中的一个函数,因此它不是一个好的名称来分配给正在加载的数据 然而,以下是您可能的处理方法: ls() ## I'm starting with nothing in my workspace # character(0) ## Here's how
if (data == null) {
data <- read.csv(file)
}
if(数据==null){
数据您可以使用exists()
,但是您还应该确保为数据集使用的名称可能不是R所能找到的。data()
是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您可以检查数据是否已经有一些属性(例如类)或它是否存在。第一种解决方案很简单,但技术上不正确;第二种解决方案有时可能很棘手,具体取决于您的环境和变量名
## Creating data
test1 <- c(1:5, "6,7", "8,9,10")
file <- tempfile()
writeLines(test1, file)
创建数据
test1您需要的是.null
,如果是大数据,请尝试fread
即库(data.table);fread(file)
谢谢!我尝试过使用fread,但遇到了一个错误。fread中的错误(“temp_prec_small.csv.bz2”,stringsafactors=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\xca2Oc\xceN\xcb\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
将其保存为压缩二进制格式,该格式应小于原始文本。由于某些原因,解决方案1不起作用。它似乎没有读取csv文件NVM,我想是b/c,我正在检查“数据”是否存在。谢谢!
## Creating data
test1 <- c(1:5, "6,7", "8,9,10")
file <- tempfile()
writeLines(test1, file)
if (!exists("data")) {
data <-read.csv(file)
}
## 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)
}