[R] Simple loop question

Noah Marconi noah.marconi at noah-marconi.com
Fri Mar 28 16:11:17 CET 2014


Here're a couple alternatives if you want to use the index instead of 
the variable name:


# Reproducible data frame

a1 <- 1:15
a2 <- letters[1:15]
a3 <- LETTERS[1:15]
a4 <- 15:1
a5 <- letters[15:1]
df <- data.frame(a1, a2, a3, a4, a5)

df

# a1 a2 a3 a4 a5
# 1   1  a  A 15  o
# 2   2  b  B 14  n
# 3   3  c  C 13  m
# 4   4  d  D 12  l
# 5   5  e  E 11  k
# 6   6  f  F 10  j
# 7   7  g  G  9  i
# 8   8  h  H  8  h
# 9   9  i  I  7  g
# 10 10  j  J  6  f
# 11 11  k  K  5  e
# 12 12  l  L  4  d
# 13 13  m  M  3  c
# 14 14  n  N  2  b
# 15 15  o  O  1  a




# Alternate 1

summary(df)

# prints the following but trims the longer summaries:

# a1             a2          a3          a4             a5
# Min.   : 1.0   a      :1   A      :1   Min.   : 1.0   a      :1
# 1st Qu.: 4.5   b      :1   B      :1   1st Qu.: 4.5   b      :1
# Median : 8.0   c      :1   C      :1   Median : 8.0   c      :1
# Mean   : 8.0   d      :1   D      :1   Mean   : 8.0   d      :1
# 3rd Qu.:11.5   e      :1   E      :1   3rd Qu.:11.5   e      :1
# Max.   :15.0   f      :1   F      :1   Max.   :15.0   f      :1
# (Other):9   (Other):9                  (Other):9




# Alternate 2

for (i in 1:length(df)) {
   print(summary(df[[i]]))
}

# prints the following:

#   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
# 1.0     4.5     8.0     8.0    11.5    15.0
# a b c d e f g h i j k l m n o
# 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
# A B C D E F G H I J K L M N O
# 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
# Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
# 1.0     4.5     8.0     8.0    11.5    15.0
# a b c d e f g h i j k l m n o
# 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1




On 2014-03-28 02:32, Jim Lemon wrote:
> On 03/28/2014 05:27 PM, Luana Marotta wrote:
>> Hi all,
>> 
>> I'm trying to find out what is the equivalent in R for the following 
>> Stata
>> code:
>> 
>> Let's say I have the variables: a1, a2, a3, a4, a5
>> 
>> forvalues i = 1(1)5 {
>>      summary a`i'
>> }
>> 
>> That is, I want to know how to loop through variables in R.
>> 
> Hi Luana,
> Try this:
> 
> for(var in paste("a",1:5,sep="")) print(summary(get(var)))
> 
> Jim
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list