[R-lang] apply through a list
Joan Bresnan
bresnan at stanford.edu
Wed May 16 14:20:22 PDT 2007
> (L[[1]] + L[[2]])/2
[,1] [,2]
[1,] 3 5
[2,] 4 6
On 5/16/07, Michael Cysouw <cysouw at eva.mpg.de> wrote:
> unfortunatly not: "lapply" applies a function to every element in a
> list - I am trying to do something with a recurrent part of each
> element in the list.
>
> For example:
>
> M1 <- matrix( 1:4, nrow=2, ncol=2)
> M2 <- matrix( 5:8, nrow=2, ncol=2)
>
> L <- list( M1, M2 )
>
> How do I apply a function to every position in the matrix through all
> matrices, say take the average. Expected result:
>
> [,1] [,2]
> [1,] 3 5
> [2,] 4 6
>
> best
> michael
>
>
> On 16 May 2007, at 21:18, Joan Bresnan wrote:
>
> > Are you looking for lapply?
> > lapply package:base R Documentation
> >
> > Apply a Function over a List or Vector
> >
> > Description:
> >
> > 'lapply' returns a list of the same length as 'X', each element of
> > which is the result of applying 'FUN' to the corresponding element
> > of 'X'.
> >
> > 'sapply' is a "user-friendly" version of 'lapply' by default
> > returning a vector or matrix if appropriate.
> >
> > 'replicate' is a wrapper for the common use of 'sapply' for
> > repeated evaluation of an expression (which will usually involve
> > random number generation).
> >
> > Usage:
> >
> > lapply(X, FUN, ...)
> >
> > sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
> >
> >
> >
> >
> > On 5/16/07, Michael Cysouw <cysouw at eva.mpg.de> wrote:
> >> a general question, not specific to linguistics...
> >>
> >> I have a (large) set of same-size matrices M1,M2,M3,... which I
> >> stored in a list. How do I apply a function over the same position of
> >> all matrices? For example, take the sum M1+M2+M3+...
> >>
> >> I have not found any "apply" like variant that would do the trick.
> >> Any suggestions?
> >>
> >> best
> >> michael
> >>
> >>
> >> —————————————————————————
> >> Michael Cysouw
> >>
> >> Department of Linguistics
> >> Max Planck Institute for Evolutionary Anthropology
> >> Deutscher Platz 6
> >> D-04103 Leipzig
> >>
> >> Room: U 1.14
> >>
> >> phone: +49 (0) 341 35 50 316
> >> fax: +49 (0) 341 35 50 333
> >> home: +49 (0) 341 22 59 488
> >> mobile: +49 (0) 172 18 33 507
> >> e-mail: cysouw at eva.mpg.de
> >> homepage: http://www.eva.mpg.de/~cysouw/
> >> —————————————————————————
> >>
> >>
> >>
> >> _______________________________________________
> >> R-lang mailing list
> >> R-lang at ling.ucsd.edu
> >> https://ling.ucsd.edu/mailman/listinfo.cgi/r-lang
> >>
> >
> >
> > --
> > Joan Bresnan
> > Stanford University
> > http://www.stanford.edu/~bresnan/
>
>
> _______________________________________________
> R-lang mailing list
> R-lang at ling.ucsd.edu
> https://ling.ucsd.edu/mailman/listinfo.cgi/r-lang
>
--
Joan Bresnan
Stanford University
http://www.stanford.edu/~bresnan/
More information about the R-lang
mailing list