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

Michael Bach phaebz at gmail.com
Thu Apr 5 13:01:51 CEST 2012


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.

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)

Thanks for your time,
Michael Bach



More information about the R-help mailing list