Skip to content
Prev 314958 / 398506 Next

Basic loop programming

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) ,
          get(paste0('s',i))/get(paste0('c',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