[R] Creating loops with strings

cls59 chuck at sharpsteen.net
Thu Sep 24 01:34:20 CEST 2009




Rakknar wrote:
> 
> Hello. I'm trying to run a series of commands in two different datasets.
> For make it efficient I want to make a loop for it. Until now the only
> command for loops i found it's the for() command it's only for series of
> numbers and not a series of strings, witch it's what i'm needing. It would
> be something like this
> 
> for(i in dataset1 dataset2) {
>             i <- read.dta("dataset1.dta")
>             ls()
>             summary(i)
>             str(i)
>             attach(i)
>             }
> 
> I hope the idea it's clear. I'm using 2.9.1 Windows Version of R.
> 
> Thanks.
> 

First, form a vector of the datasets you want to load:

data.sets <- c( 'dataset1', 'dataset2' )

Then execute your loop:

for( set.name in data.sets ){

  data.file <- paste( set.name, sep='' )

  assign( set.name, read.dta( file.name ), envir = .GlobalEnv )

  ls( envir = .GlobalEnv )

  summary( get( set.name, envir = .GlobalEnv ))

  str( get( set.name, envir = .GlobalEnv ))

}

Here, the assign() function is used to create a variable in the top-level
environment (given by .GlobalEnv) that has the same name as the current
value of set.name-- so two variables named dataset1 and dataset2 will be
generated by the loop. The contents of those variables are set to the return
value of read.dta().

Next, the get() function is used to retrieve the variables created by
assign() using the name stored in set.name-- this retrieved object is then
passed off to summary() and str().

Notice that I have excluded the attach() statement, although it could have
been applied to the datasets being loaded. Attach should only be used in
situations where you intend to use, but not modify, the contents of a list
or data frame. Even then it often produces results similar to shooting
yourself in the foot with a .44 magnum.

Hope this helps!

-Charlie

-----
Charlie Sharpsteen
Undergraduate
Environmental Resources Engineering
Humboldt State University
-- 
View this message in context: http://www.nabble.com/Creating-loops-with-strings-tp25530899p25531328.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list