[R] Help with looping

Mark Sharp msharp at txbiomed.org
Tue Feb 17 23:26:59 CET 2015


Alexandra,

According to the documentation (?readLines), readLines returns a character vector with one line from the file being read in each element of the vector. You can put the character vector from each file (as represented by a year designation in your example) in a separate list element. You want to count the elements in the list starting at 1 not 2000. The integers from years[i] get converted to strings in sprintf in the code below.

years <- 2000:2003
Data <- list(length(years))

for (i in seq_along(years)){
    #script for downloading each year
    Data[i] = readLines(sprintf('file/%s',years[i]))
}
# Data[1] will have the character vector made up of the lines in 'file/2000'.

Mark

R. Mark Sharp, Ph.D.
Director of Primate Records Database
Southwest National Primate Research Center
Texas Biomedical Research Institute
P.O. Box 760549
San Antonio, TX 78245-0549
Telephone: (210)258-9476
e-mail: msharp at TxBiomed.org







> On Feb 17, 2015, at 12:15 PM, Alexandra Catena <amc5981 at gmail.com> wrote:
>
> Hi,
>
> I need help with a for loop and printing data.  I want to loop through a
> few years and print the data from each year stacked on top of each other.
> For example,
>
> for (i in 2000:2003){
> #script for downloading each year
> Data = readLines(sprintf('file/%4i,i))
> }
>
> It only prints out the data from the last year.  Also, I tried
>
> Data[i] =  readLines(sprintf('file/%4i,i))
>
> but it says:
>
> "number of items to replace is not a multiple of replacement length"
>
> How do I get it to not replace each year of data? I have R version 2.15.1
>
> Thanks,
> Alexandra
>
>       [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.


NOTICE:  This E-Mail (including attachments) is confidential and may be legally privileged.  It is covered by the Electronic Communications Privacy Act, 18 U.S.C.2510-2521.  If you are not the intended recipient, you are hereby notified that any retention, dissemination, distribution or copying of this communication is strictly prohibited.  Please reply to the sender that you have received this message in error, then delete it.



More information about the R-help mailing list