[R] Basic Looping Trouble

Petr Savicky savicky at praha1.ff.cuni.cz
Tue Mar 22 08:26:55 CET 2011


On Mon, Mar 21, 2011 at 02:28:32PM -0700, armstrwa wrote:
> Hi all,
> 
> Forgive me for this basic question.  I've been doing some research and
> haven't been able to figure out how to best do this yet.
> 
> I have 75 variables defined as vector time series.  I am trying to create a
> script to automate calculations on each of these variables, but I wasn't
> sure how to go about calling variables in a script.
> 
> I am hoping to write a loop that calls a list of variable names and runs
> several tests using each of the datasets I have entered.
> 
> For example, say I have a defined 5 variables: var1, var2,...var5.  How
> could I create a script that would run, say, a MannKendall correlation test
> on each variable?

Hi.

A typical way, how to perform a loop over several variables, is
to keep the variables in a list. For example

  lst <- list(var1=2:5, var2=c(23, 56), var3=seq(0, 1, length=11))
  lst

  $var1
  [1] 2 3 4 5

  $var2
  [1] 23 56

  $var3
   [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

  for (i in seq.int(along=lst)) {
      print(mean(lst[[i]]))
  }

  [1] 3.5
  [1] 39.5
  [1] 0.5

It is also possible to loop over isolated variables. For example

  var1 <- 2:5
  var2 <- c(23, 56)
  var3 <- seq(0, 1, length=11)
  for (varnam in c("var1", "var2", "var3")) {
      x <- get(varnam)
      print(mean(x))
  }

Hope this helps.

Petr Savicky.



More information about the R-help mailing list