Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create empty object in R

Tags:

object

r

I'm trying to create empty numeric object like this

corr <- cor()

to use it later on in a loop. but, it keep returning this error Error in is.data.frame(x) : argument "x" is missing, with no default.

Here is my full script:

EVI <- "D:\\Modis_EVI\\Original\\EVI_Stack_single5000.tif"
y.EVI <- brick(EVI)
m.EVI.cropped <- as.matrix(y.EVI)
time <- 1:nlayers(y.EVI)
corr <- cor()

inf2NA <- function(x) { x[is.infinite(x)] <- NA; x }
for (i in 1:nrow(m.EVI.cropped)){
        EVI.m   <- m.EVI.cropped[i,]
        time    <- 1:nlayers(y.EVI) 
        Corr[i] <- cor(EVI.m, time, method="pearson", use="pairwise.complete.obs")
}

Any advice please?

like image 626
NAmo Avatar asked Mar 11 '23 12:03

NAmo


2 Answers

Since you are asking for advice:

It is very likely that you don't need to do this since you can probably use (i) a vectorized function or (ii) a lapply loop that pre-allocates the return object for you. If you insist on using a for loop, set it up properly. This means you should pre-allocate which you can, e.g., do by using corr <- numeric(n), where n is the number of iterations. Appending to a vector is extremely slooooooow.

like image 64
Roland Avatar answered Mar 24 '23 11:03

Roland


We can create empty objects with numeric(0), logical(0), character(0) etc.

For example

num_vec <- numeric(0)

creates an empty numeric vector that can be filled up later on:

num_vec[1] <- 2
num_vec
# [1] 2
num_vec[2] <- 1
num_vec
# [1] 2 1
like image 42
symbolrush Avatar answered Mar 24 '23 10:03

symbolrush