[R] Help

Joshua Wiley jwiley.psych at gmail.com
Fri Nov 11 21:56:29 CET 2011


Hi Francesca,

Try something like this:

x <- c(1, 3, 7)
dati <- lapply(1:4, function(i) {datiP[datiP$city == i, x]})

dati[[1]] # datiP1
dati[[2]] # datiP2
dati[[3]] # datiP3
dati[[4]] # datiP4

if the *only* groups are 1, 2, 3, 4 (i.e., 1:4 is exhaustive), this
can be simplified:


dati <- by(datiP, datiP$city, `[`, x)

For documentation, see:

?lapply
?by
?"[" # to see how I use the extraction operator as a function

Hope this helps,

Josh

On Fri, Nov 11, 2011 at 12:24 PM, Francesca
<francesca.pancotto at gmail.com> wrote:
> Dear Contributors
> I would like to perform this operation using a loop, instead of repeating
> the same operation many times.
> The numbers from 1 to 4 related to different groups that are in the
> database and for which I have the same data.
>
>
>    x<-c(1,3,7)
>
> datiP1 <- datiP[datiP$city ==1,x];
>
> datiP2 <- datiP[datiP$city ==2,x];
>
> datiP3 <- datiP[datiP$city ==3,x]
>
> datiP4 <- datiP[datiP$city ==4,x];
> --
>
> Thank you for any help you can provide.
>
> Francesca
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list