Reputation: 73
Can anyone tell my while my for loop in r is just running once? The script is just attempting to create csv files for a list of about 200 subfiles within about 5 major files. Here is my code :
ImpactGrid<- function(num, condition, CONDITION){
#Set working directiory
for(i in num){
if(i <10){
filename <- paste("./EOBS DATA/ECA_blend_", condition, "/" ,CONDITION, "_STAID00000", i, ".txt", sep = "")
}
if(i >=10 & i < 100){
filename <- paste("./EOBS DATA/ECA_blend_", condition, "/" ,CONDITION, "_STAID0000", i, ".txt", sep = "")
}
if(i>= 100){
filename <- paste("./EOBS DATA/ECA_blend_", condition, "/" ,CONDITION, "_STAID000", i, ".txt", sep = "")
}
con <- file(filename, "r")
data <- readLines(con)
close(con)
q <- data[21:length(data)] # removes non data before the data begins
Impactdata <- read.table(text = q, sep=',',fill=TRUE,colClasses='character',header = TRUE )
Savename <- paste("./EOBS DATA/",condition, "_csv_data/", condition,i, ".csv", sep = "")
write.csv(Impactdata, Savename)
x <- read.csv(paste("./EOBS DATA/",condition, "_csv_data/", condition,i, ".csv", sep = ""))
return(head(x))
}
}
Upvotes: 0
Views: 623
Reputation: 7592
If you are trying to go from 1 to num
, the code is:
for(i in 1:num)
for
loops iterate over a vector but num
has a length 1 so it iterates only 1 time.
You also need to remove the return
statement from the body of the loop. Otherwise, it will always exit the first time it hits return.
Upvotes: 3
Reputation: 113
While I think the 1:num is a good answer and may be a problem, it looks like the for loop encompasses everything including the last return() statement. So even if num were a vector, it'd only loop once through all the code and return() from the function after one loop.
Upvotes: 1