-2

when i use command print in my loop i have 6140 raws:

for (i in 1:614 ){
print(paste(urls[i], 0:10)))
}

but i don't know how extract all values to data frame When I tru create variable :

for (i in 1:614 ){
 a<- as.data.frame(paste(urls[i], 1:10))
  }

i have only 10 obj wit my links.

In general, i want have 6140 obj with my data

P.S.sorry for my english :)

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
  • what is `urls`? A character vector? A data frame? A list? If it's a data frame, have a look at [this existing answer](http://stackoverflow.com/questions/11121385/repeat-rows-of-a-data-frame). – hrbrmstr Jan 11 '15 at 11:40
  • urls is character vector – Kostiantyn Palianychka Jan 11 '15 at 11:49
  • 3
    `data.frame(rep(urls, each=10))` will give you a data frame with each element of the `urls` vector repeated 10 times. If you plan to do any real work in R, you'll benefit from taking a look at how to do vectorized operations. The [R tag wiki](http://stackoverflow.com/tags/r/info) here on SO is a good place to start for resources to learn R better. – hrbrmstr Jan 11 '15 at 11:58

1 Answers1

1

I would say the easiest way to do what you want is to use the foreach package. It provides a .combine argument that makes joining together the results from each cycle super easy.

# Create a reproducible example of urls
urls <- rep_len (letters, 614)

# Install and load `foreach`
install.packages ("foreach")
library (foreach)

# Create the loop and indicate that you want to join the results by row
a <- foreach (i=1:614, .combine = rbind) %do% {
  as.data.frame (paste(urls[i], 0:10))
}

That's it. You can combine the results in many kinds of classes (vectors, data frames, lists, etc) and ways (by row, by column, etc). Learning to use foreach won't only be beneficial for this problem, but it will be also very useful, if later you need to do some kind of parallel computation.

If you want to stick to a traditional loop, one of the many ways to do it is:

a <- data.frame ()
for (i in 1:614){
  a <- rbind (a, as.data.frame (paste(urls[i], 0:10)))
}

Happy coding!

  • 1
    Nice solution. (+1). But, the vectorized solution `data.frame(paste(rep(urls, each=11), 0:10))` given by @hrbrmstr is much better in this case, IMHO. – Khashaa Jan 11 '15 at 15:47