[R] nested for loop

jim holtman jholtman at gmail.com
Wed Jul 18 20:19:41 CEST 2007


This should create your files for you:

x <- 1:1080  # test data
# create a vector of 30 consecutive values for spliting the data
breaks <- rep(1:ceiling(length(x) / 30), each=30)[1:length(x)]
# now partition the data into 30 values and write them
fileNo <- 1  # initialize the file number
invisible(lapply(split(x, breaks), function(.values){
    write(.values, file=sprintf("NWRxx.%03d.txt", fileNo))
    fileNo <<- fileNo + 1   # update the file number
}))


On 7/18/07, Sherri Heck <sheck at ucar.edu> wrote:
> Hi,
>
> I am new to programming and R.  I am reading the manual and R books by Dalgaard and Veranzo to help answer my questions but I am unable to figure out the following:
>
> I have a data file that contains 1080 data points. Here's a snippet of the file:
>
> [241]  0.3603704000  0.1640741000  0.2912963000   NA  0.0159259300  0.0474074100
>
> I would like to break the file up into 30 consecutive data point segments and then write each segment into a separate data file.  This is one version of code that I've tried.
>
> mons = c(1:12)
>
> data = scan(paste("C:/R/NWR.txt"))
> for (mon in mons)  {
>  for (i in c(1:30)) {
>  for (j in data)    {
>
> write((data),paste(mon,'NWR dc_dt_zi ppm meters per sec.txt',sep=''),ncol=1)
>
> }
>  }
>  }
>
> I think I'm really close, but no cigar.  Thanks in advance for any help-
>
> S.Heck
> Graduate Research Assistant
> University of Colorado, Boulder
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>


-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list