LaVOZs

The World’s Largest Online Community for Developers

'; r - Apply a function to every nth element in vector - LavOzs.Com

I have a vector in R:

> v <- c(5, 10, 15, 20, 25, 30, 35, 40, 45, 50)

I would like to apply a function to every nth element of the vector and have it return the new vector. For example, let's say I would like to multiply every third element of the vector by 2. I would then get

> v
[1] 5 10 30 20 25 60 35 40 90 50

I have managed to extract elements using vector logic:

> v[c(rep(FALSE,2),TRUE)]
[1] 15 30 45

meaning I have figured out how to access the elements and I am able to do things to them, but I don't know how to get them back into my original vector v.

We need to assign

v[c(FALSE, FALSE, TRUE)] <- v[c(FALSE, FALSE, TRUE)]*2

Another option would be to use seq. You specify n at will, and seq will start a sequence at n, by n until the end of your vector (length(v)).

n <- 3
v[seq(n, length(v), n)] <- v[seq(n, length(v), n)]*2

> v
 [1]  5 10 30 20 25 60 35 40 90 50

Solution using ifelse:

ifelse(1:length(v) %% 3 == 0, v * 2, v)
# [1]  5 10 30 20 25 60 35 40 90 50

Using tidyverse:

    library(tidyverse)
    p <- seq(v) %% 3 == 0
    f <- function(x) x*2
    map_if(v, p, f) %>% as_vector

Using a while loop:

i=0  
while (i < (length(v)-1) ){
    i=i+3
    v[i]=v[i]*2
}

> v
 [1]  5 10 30 20 25 60 35 40 90 50
Related
Test if a vector contains a given element
Counting the number of elements with the values of x in a vector
What is the easiest way to initialize a std::vector with hardcoded elements?
Grouping functions (tapply, by, aggregate) and the *apply family
Apply a function to every row of a matrix or a data frame
Extract every nth element of a vector
How to apply a function to each element of a vector in R
Adding value after every nth element of vector in R
Rearrange vector every nth column