[R] Basic loop programming

MacQueen, Don macqueen1 at llnl.gov
Wed Jan 9 22:57:57 CET 2013

Yes, R is a different language, and has different syntax and different
built-in functions, so, yes it works differently.

If you want to do it the same way in R as in that other language, you have
to use a different method for constructing the variable names inside the
loop. Here's an example, using the get() and assign() functions to
construct the variable names, essentially replacing your constructions
like  Customers_2012_'i'.

I have four variables, named
  s01, s02
  c01, c02
(sales and customers for two months)

Something like this should do it:

for (i in c('01','02')) {
  assign( paste0('r',i) ,

I should now have new variables r01 and r02.

This is not tested, so hopefully I got all the parentheses matched.

Of course, that looks cumbersome and ugly, and it is. There are other ways
in R to store your data, for which the code will be much friendlier.

If you use
   i in 1:12
you are creating numbers, but your variable names use character strings,
'01','02', etc. So, no, you can't use
  i in 1:12
directly. But you can use i in 1:12 if you use a formatting function on i
to convert it to a character string with leading zeros. The formatC
function is one such function; there are others.


Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550

On 1/9/13 8:02 AM, "Paolo Donatelli" <donatellipaolo at gmail.com> wrote:

>Hi all,
>newbie question: I am trying to set up a very simple loop without
>Let's say I have monthly observation of two variables for a year
>- Sales_2012_01, Sales_2012_02, Sales_2012_03, ....      (total sales
>for jan 2012,feb 2012, etc.)
>- Customers_2012_01, Customers_2012_02, ....  (total number of
>customers for jan 2012, etc.)
>and I want to create new monthly variables in order to compute
>revenues per customers:
>Av_revenue_2012_01 = Sales_2012_01 / Customers_2012_01
>Av_revenue_2012_02 = Sales_2012_02 / Customers_2012_02
>how can I proceed?
>In other programming language I used just to write something like
>for (i in list("01","02, ..., "12") {
>Av_revenue_2012_'i' = Sales_2012_'i' / Customers_2012_'i'
>but in R it seems not to work like that. Further, and correct me if I
>am wrong, I cannot use simple (i in 1:12) since I have a 0 digit in
>front of the single-digit months.
>thanks in advance for your help
>R-help at r-project.org mailing list
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list