Ty Royce
Ty Royce

Reputation: 1

Beginner for loop in R not looping

Thanks for reading this entry. I am a beginner R student and have a for() that will not loop thru all of my entries.

for (i in 1:9){
maximum<-max(read.csv(paste("data2013010",i,".csv", sep=""),row.names=1))
print(paste("The max of data2013010",i,".csv"," is", maximum))
}

[1] "The max of data2013010 9 .csv  is 1014.5"

I can't seem to get this function to loop thru all 9 values in my vector. My first guess is I may need to utilize a counter, am I on the right track or is my code missing a key element?

Note: This has to be a for() loop

Upvotes: 0

Views: 88

Answers (1)

Adam B.
Adam B.

Reputation: 1180

Are you running the whole for loop? Seems to work fine for me when I try to recreate your problem.

Also, if you're just starting with R, I'd recommend learning the tools from the tidyverse package. They make your code much simpler and easier to read (and find bugs in).

For example, your for loop can be rewritten in the following way using tidyverse:


# Put names of all .csv files that start with "data2013010" into a vector called "data_files"

data_files <- list.files() %>% 
  str_extract('^data2013010\\d+\\.csv') %>% 
  na.omit()

# Iterate across the data_files vector to find the maximum of each element

purrr::map(data_files, ~ read_csv(.x) %>%
             max(.))

Upvotes: 1

Related Questions