4

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.

zx8754
  • 52,746
  • 12
  • 114
  • 209
echoecho
  • 75
  • 1
  • 8
  • Related post: https://stackoverflow.com/questions/5237557/extracting-every-nth-element-of-a-vector – zx8754 Nov 29 '17 at 10:29

5 Answers5

8

We need to assign

v[c(FALSE, FALSE, TRUE)] <- v[c(FALSE, FALSE, TRUE)]*2
akrun
  • 874,273
  • 37
  • 540
  • 662
6

Solution using ifelse:

ifelse(1:length(v) %% 3 == 0, v * 2, v)
# [1]  5 10 30 20 25 60 35 40 90 50
pogibas
  • 27,303
  • 19
  • 84
  • 117
5

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
LAP
  • 6,605
  • 2
  • 15
  • 28
3

Using tidyverse:

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

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
user 123342
  • 463
  • 1
  • 9
  • 21
  • 3
    A bit overkill to use loops on a vector, with this logic we can add forloop, apply family functions solutions, too. – zx8754 Nov 29 '17 at 10:31