Skip to content

Loop on characters

3 messages · Megh Dal, jdeisenberg, Phil Spector

#
Hi,

suppose I have three vectors like :

l1 = 1:4
l2 = 4:9
l3 = 16:67

now I want to construct a loop like :

for (i in 1:3)
   {
     count1[i] = length(li) # i.e. it will take l1, l2, l3 according to
value of i
   }

Can anyone please tell me how to do that?

Regards,
#
megh wrote:
Try this. There's probably a more elegant way to do it, but this works.

l1 <- 1:4; l2 <- 4:9;  l3 <- 16:67
count1 <- c( ) # start with an empty vector
for (i in 1:3) count1[i] <- length(get(paste("l",i,sep="")))
count1

The call to paste( ) concatenates the letter "l" and value of i; they are
separated by the null string (otherwise they would have the default blank
separator between them).  The call to get( ) fetches the object with that
name.
#
megh -
    The best way to organize similar objects in R is to
put them into a list.  If you keep this in mind when you're
first organizing your data, it's no harder than giving each object
a separate name.  For example
The reason that this is a good idea in R is that functions
like sapply, lapply, and mapply automatically operate on each
element of a list, and return the answer in a suitable R object. 
(Note that in your example, you would get an error because you 
hadn't defined count1.  And why should you?)

So the answer you want is
[1]  4  6 52

Hope this helps.
                                        - Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu
On Tue, 10 Feb 2009, megh wrote: