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

David Winsemius dwinsemius at comcast.net
Thu Apr 5 15:53:55 CEST 2012


On Apr 5, 2012, at 7:01 AM, Michael Bach 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.
>
> 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)

An alternate approach to the ifelse() solutions you have been offered  
is to use identical indexing on both sides of an assignment function.

 > v <- c(1, 2, 3, 4)
 > w <-v
 > w[seq(2, length(w), by =2)] <-w[seq(2, length(w), by =2)]^2
 > w
[1]  1  4  3 16

If you still wanted to create a function that would square each  
element "in place" you could do this with an indexing strategy:

  v <- c(1, 2, 3, 4)
  w <-v
  mysqr <- function (x) { eval.parent(substitute(x <- x^2))  }
  mysqr(w[seq(2, length(w), by =2)])
  w
#[1]  1  4  3 16

(Credit: http://www.statisticsblog.com/2011/10/waiting-in-line-waiting-on-r/ 
  and search on 'inc')

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

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list