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.

1

5 Answers 5

8

We need to assign

v[c(FALSE, FALSE, TRUE)] <- v[c(FALSE, FALSE, TRUE)]*2 
Sign up to request clarification or add additional context in comments.

Comments

6

Solution using ifelse:

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

Comments

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 

Comments

3

Using tidyverse:

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

Comments

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 

1 Comment

A bit overkill to use loops on a vector, with this logic we can add forloop, apply family functions solutions, too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.