简体   繁体   中英

Automate reading of CSV files in R

I'm working with NOAA's database of storm events - 1951 to 2015. Code and CSVs in link. https://www.dropbox.com/sh/lb69l5isa25guc2/AAC4-gYr3N6TVDxEGzBB8fJVa?dl=0

The code is done, but I had to repeat the following two lines 65 times, changing only a couple things manually:

x52 <- read.csv("StormEvents_details-ftp_v1.0_d1952_c20160223.csv")
n52 <- length(select(x52, EVENT_TYPE) %>% filter(EVENT_TYPE=="Tornado") %>% unlist)

Is there a way to tell R to assign each new CSV you read to a new vector (for 1953, 54 etc), and to perform the same operations on all of them? I found this thread but I don't it's exactly the same question: Working with Large Number of csv files in R

Thanks

I assume you have all the files and put them in one directory. You could do something similar to this:

datFiles <- c(list.files(path = "c:/Users/Philip/Downloads/Tornadoes/",
    pattern = "StormEvents_details.*\\.csv$",
    all.files = FALSE, full.names = TRUE, recursive = FALSE, ignore.case = TRUE,
    include.dirs = FALSE, no.. = FALSE))

for (i in 1:length(datFiles)) {
    x[i] <- read.csv(datFiles[i])
    n[i] <- length(select(x[i], EVENT_TYPE) %>% filter(EVENT_TYPE=="Tornado") %>% unlist)
    <your code here>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM