[R] Loop on characters

jdeisenberg catcode at catcode.com
Wed Feb 11 08:03:21 CET 2009




megh wrote:
> 
> 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
>    }
> 

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.


-- 
View this message in context: http://www.nabble.com/Loop-on-characters-tp21949173p21949383.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list