[R] Printing a variable in a loop
Miguel Manese
jjonphl at gmail.com
Thu Jun 28 08:35:31 CEST 2012
Hi Kat,
On Thu, Jun 28, 2012 at 8:22 AM, kat_the_great <knv4 at hotmail.com> wrote:
> Dear R Users:
>
> I'm a STATA user converting to R, and I'd like to be to do the following.
> #Assign var_1 and var_2 a value
> 10->var1
> 20->var2
>
> #Now I'd like to print the values of var_1 and var_2 by looping through
> var_1 and var_2 in such a manner:
>
> while(y<3){
> print(var_y)
> y+1->y
> }
The nearest you can get is
while (y < 3) {
print(.GlobalEnv[[paste("var", y, sep="")]])
y <- y + 1
}
.GlobalEnv (a list, or strictly speaking an environment) contains all
variables at the top-level of the REPL
But this is not how we do it in R.
1. if you want to "display" the variable, just type it
> var1
2. In Stata, you are working with one (tabular) data set at any time.
In R, you can work with multiple data sets (R construct: dataframes)
at the same time. For example using the builtin anscombe data set
Stata:
use anscombe
di x1 y1 x2 y2 // display all
di x1 y1 x2 y2 if _n <= 10
R:
# data(anscombe) # optional
anscombe[, c("x1", "y1", "x2", "y2")] # index by column
anscombe[1:10, c("x1", "y1", "x2", "y2")] # index by row & column
head(anscombe[, c("x1","y1","x2","y2")], n=10] # same as above
Regards,
Jon
More information about the R-help
mailing list