简体   繁体   中英

Delete all values of a vector except certain indexes

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM