Reputation: 680
I have a long vector (its type is character). I want to delete all the values except the ones that their indexes are multiple of 7
. For example, if the length of my vector is 100
, I want to have all cells empty except 7, 14, 21,..., 98
cells.
Appreciate
Upvotes: 0
Views: 290
Reputation: 545618
In R you can use either integers or a logical vector as an index (or a character vector for named access).
Your problem can be solved using either; for instance, you can generate an integer vector of the numbers 7, 14, … using seq
:
index = seq(7L, length(x), by = 7L)
Or you can generate a logical vector that’s TRUE
if and only if the corresponding integer index is divisible by 7:
index = seq_along(x) %% 7L == 0L
Either way, you then use that index to subset your data:
x[index]
Or, if you want to retain the other values but “empty” them (what does “empty” mean, though?) you can assign an empty value to them:
x[! index] = NA_character_ # or "", or something else.
Upvotes: 3