[R] Variable as a filename

baptiste auguie baptiste.auguie at googlemail.com
Wed Sep 23 12:07:13 CEST 2009


Hi,

The short answer would be ?paste (as in paste(year, ".csv", sep="") ),
but I'd suggest you try this instead,

lf <- list.files(pattern = ".csv")

lf
# [1] "2003.csv" "2004.csv" "2005.csv"

ln <- gsub(".csv", "", lf)

ln
# [1] "2003" "2004" "2005"

length(ln)

lapply(lf, read.csv)

?list.files
?lapply

HTH,

baptiste

2009/9/23 Lucas Sevilla García <luckoctober at hotmail.com>:
>
> Hi R community, I have a question. I have 5 files in a directory. Each file has a year as a name (file 1 ->2004, file 2-> 2005, ...). I want to build a for loop where I call first file, do some calculations, go to second file, do some calculations, etc. Somethin like this:
>
> year<-2003
> nfiles <- length(dir())
>
> for( year in 2003:nfiles)
>    {clima<-read.csv2([year]".csv", nrows=10)
>    }
>
> As you see, file name has to change when I read a year, in other words, if a read 2004 in variable year, I need to select file 2004. Then I read 2005 in variable year, and then I R have to open file 2005,...That's my question, How can I write the order read.csv2 in a way to obtain the file correspondant to the year read in the for loop. Thanks in advance.
>
> Lucas
>
> _________________________________________________________________
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list