corr <- function(directory, threshold = 0) { setwd("c:/users/hp1/desktop") files_full <- list.files(directory,full.names = true) cr <- data.frame() j = 1 for(i in 1:332) { y <- read.csv(files_full[i]) z <- y[complete.cases(y),] if (nrow(z) > threshold){ cr[j] <- cor(z[,'sulfate'], z[,'nitrate'], method = "pearson") j = j+1 } } cr } it's showing following error: error in [<-.data.frame(*tmp*, j, value = -0.222552560758546) : replacement has 1 row, data has 0 expecting j increments, values added cr dtaframe. not happening. please suggest necessary changes
you try this. if provide reproducible example can show how clean result. sapply try simplify result, can stop specifying simplify = false , remove unwanted list elements.
setwd("c:/users/hp1/desktop") # use outside function corr <- function(directory, threshold = 0) { files_full <- list.files(directory, full.names = true) sapply(files_full, fun = function(x) { y <- read.csv(x) z <- y[complete.cases(y),] if (nrow(z) > threshold){ out <- cor(z[,'sulfate'], z[,'nitrate'], method = "pearson") } else { return(na) # or other way want handle result } }) }
Comments
Post a Comment