Select every other element from a vector

前端 未结 3 1459
逝去的感伤
逝去的感伤 2020-11-29 03:56

Let\'s say I had a vector:

remove <- c(17, 18, 19, 20, 24, 25, 30, 31, 44, 45).

How do I select / extract every second value in the vector? L

相关标签:
3条回答
  • 2020-11-29 04:20
    remove[seq(1,length(remove),2)]
    
    0 讨论(0)
  • 2020-11-29 04:27

    Just another alternative:

    > remove[seq_along(remove) %% 2 > 0]
    [1] 17 19 24 30 44
    
    0 讨论(0)
  • 2020-11-29 04:42
    remove[c(TRUE, FALSE)]
    

    will do the trick.


    How it works?

    If logical vectors are used for indexing in R, their values are recycled if the index vector is shorter than the vector containing the values.

    Here, the vector remove contains ten values. If the index vector c(TRUE, FALSE) is used, the actual command is: remove[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE)]

    Hence, all values with odd index numbers are selected.

    0 讨论(0)
提交回复
热议问题