# [R] Loop on characters

Phil Spector spector at stat.berkeley.edu
Wed Feb 11 09:08:16 CET 2009

```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

> l = list(l1,l2,l3)

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

> count1 = sapply(l,length)
> count1
[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:

>
> 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,
>
> --
> View this message in context: http://www.nabble.com/Loop-on-characters-tp21949173p21949173.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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