[R] Apply function to every 'nth' element of a vector

Ista Zahn istazahn at gmail.com
Thu Apr 5 13:15:40 CEST 2012


Good morning Michael,

On Thu, Apr 5, 2012 at 7:01 AM, Michael Bach <phaebz at gmail.com> wrote:
> Dear R users,
>
> 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.

Use indexing, or ifelse.

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

Here is one way:

 w <- ifelse(v %in% seq(1, length(v), 2), v, v^2)

Best,
Ista

>
> Thanks for your time,
> Michael Bach
>
> ______________________________________________
> 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