My code:
if (data == null) {
data <- read.csv(file)
}
Reading from a big data file, which is why it would be nice to read it only once.
My code:
if (data == null) {
data <- read.csv(file)
}
Reading from a big data file, which is why it would be nice to read it only once.
You can use exists()
, but you should also make sure that you are using a name for your dataset that might not be found by R. data()
is a function in R, so it's not really a good name to assign to the data you're loading.
Nevertheless, here's how you might approach it:
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"
Here's what happens if we have a data.frame
in our environment (like you've read it in already).
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
As others have mentioned, though, you can also look at saving the data in a an "rdata" or "rds" format that can be loaded quickly.
You can either check if the data has already some attributes (for example a class) or if it exists. The first solution is easy but technically not correct; the second solution can sometimes be tricky depending on your environment and variable names
## 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)
}