0

If I have a vector such as:

vector <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)

how would I change it for every other element to be one number? For example:

vector <- c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)

Would a for loop work best? I'm not sure how to make it every 2 elements.

Thanks!

benson23
  • 16,369
  • 9
  • 19
  • 38
bella
  • 9
  • 1

2 Answers2

2

We can modify inplace with a recycling logical index:

vector <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
vector[c(FALSE, TRUE)]<-2

Or use the modulo operator with replace

replace(vector, seq_along(vector)%%2==0, 2)

 [1] 1 2 1 2 1 2 1 2 1 2
GuedesBF
  • 8,409
  • 5
  • 19
  • 37
2

This is not necessary to perform with a loop. We can use square brackets ([]) to index the vector, when the position of the element can be divided by 2 (%% 2 == 0), change the element to 2.

vector[seq_along(vector) %% 2 == 0] <- 2

[1] 1 2 1 2 1 2 1 2 1 2
benson23
  • 16,369
  • 9
  • 19
  • 38