Search code examples
rvectorindexing

How to take every 3rd element of vector x and save them to a new vector called y? (In R)


Problem: You are given a vector called x. Write a Code that takes every 3rd element of x and saves them to a new vector called y. Then raise the value of every element in y by 3.

Attempted solution:

x[seq(from=3,to=length(x),by=3)]-> y
y<-y+3

Am I even close with this?


Solution

  • your goal is a bit unprecise, however it seems that you would like to start with the first element of x, and your solution is starting with the 3rd.

    Therefore, you should go with something like :

    y <- x[seq(1, length(x), 3)]
    

    in addition, you may encounter issue if the length of x <3 in your example (seq would then expect a negative value for the "by" argument).

    in my example, you still would have an issue if x is NULL