[R] Apply function to every 'nth' element of a vector
ken knoblauch
ken.knoblauch at inserm.fr
Thu Apr 5 14:02:16 CEST 2012
ken knoblauch <ken.knoblauch <at> inserm.fr> writes:
>
> Michael Bach <phaebz <at> gmail.com> writes:
> > how do I e.g. square each second element of a
> vector with an even
> > number of elements? Or more generally to
> apply a function to every
> > 'nth' element of a vector. I looked into the
> apply functions, but
> > found no hint.
> > For example:
> > v <- c(1, 2, 3, 4)
> > mysquare <- function (x) { return (x*x) }
> > w <- applyfun(v, mysquare, 2)
> > then w should be c(1, 4, 3, 16)
> > Michael Bach
>
> Hi Michael,
>
> v^(2 - seq_along(v) %% 2)
>
> [1] 1 4 3 16
>
> Ken
>
Actually, combining Ista and my responses,
a general response could be
something like
ifelse(v %% n, v, function(v){} )
where you have set n and define some
function
HTH,
Ken
--
Ken Knoblauch
Inserm U846
Stem-cell and Brain Research Institute
Department of Integrative Neurosciences
18 avenue du Doyen Lépine
69500 Bron
France
tel: +33 (0)4 72 91 34 77
fax: +33 (0)4 72 91 34 61
portable: +33 (0)6 84 10 64 10
http://www.sbri.fr/members/kenneth-knoblauch.html
More information about the R-help
mailing list