简体   繁体   中英

Reading multiple csv files and getting the filename of each csv file in R

I am trying to read multiple csv files and do some plotting for each file using ggplot. I want to print the figures using the filename of each input file. Each csv file has 6 columns, but Im only plotting columns 1,2,5,6.

I have a code but only works for a single csv file:

    dat<-read.csv("D135_tmin.csv",header=TRUE)
    dat$Year<-seq(ymd('1991-01-01'),ymd('2000-12-31'),"days")
    dat2 <- dat[,c(1,2,5,6)]
    names(dat2)[3:4] <- c("P10","P90")
    dat2 <- melt(dat2,id.vars="Year")
    ggplot(dat2[dat2$variable=="Tmin",],aes(Year,value))+
    geom_line(linetype="dashed",color="black",size=0.25)+
    geom_point(data=dat2,aes(Year,value,grp=variable,fill=variable),pch=21,size=2)+
    scale_fill_manual(name="Legend",values=c("Tmin"="dark slate blue","P90"="green","P10"="orange"))
    dev.print(pdf, file="D135_tmin.pdf")

When reading multiple csv files, I use these commands:

     temp=list.files(pattern="*.csv")
     myfiles=lapply(temp,read.table,header=TRUE)

My problem is, I will be reading 100 csv files and the output pdfs should have the same name as the input csv files.

Any suggestions?

Is there a reason you don't want to use a for loop? You could do:

 for (i in list.files(pattern="*.csv"){
    dat <- read.csv(i) 
    dat$Year<-seq(ymd('1991-01-01'),ymd('2000-12-31'),"days")
    dat2 <- dat[,c(1,2,5,6)]
    names(dat2)[3:4] <- c("P10","P90")
    dat2 <- melt(dat2,id.vars="Year")
    ggplot(dat2[dat2$variable=="Tmin",],aes(Year,value))+
          geom_line(linetype="dashed",color="black",size=0.25)+
    geom_point(data=dat2,aes(Year,value,grp=variable,fill=variable),
      pch=21,size=2)+
      scale_fill_manual(name="Legend",values=
         c("Tmin"="dark slate blue","P90"="green","P10"="orange"))
     dev.print(pdf, file=sub("csv", "pdf", i))
 }

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