89_Simple
89_Simple

Reputation: 3805

generating index values of a vector in R

I have a vector that could be of any length. for e.g.

my_vec <- c(179, 192, 230, 243, 264, 276)

I generate another vector which is basically an index going from 0 to N. the length of this vector is equal to the length between min(my_vec):max(my_vec) as shown below:

dat <- data.frame(my_vec = min(my_vec):max(my_vec),
                  index_vec = seq_along(min(my_vec):max(my_vec)) - 1)

So 179's index is 0, 180's is 1, 181's is 2....276's is 97 etc.

I want to create two vector: a start and end which shows for each element in my_vec the starting index and the ending index. For e.g what is the index of 179 & 192, 193 & 230, 231 & 243, 244 & 264, 265 & 276. I have the following code that does it.

end_vec <- rep(NA, length(my_vec) - 1)
  
for(i in 2:length(my_vec)){
 
    temp <- dat[which.max(dat$my_vec >= my_vec[i]), ]       
    end_vec[i] <- temp$index_vec
}


end_vec <- na.omit(end_vec)

start_vec <- end_vec[-length(end_vec)] + 1
start_vec <- c(0, start_vec)
start_vec
# 0 14 52 65 86
end_vec
# 13 51 64 85 97

Though this method works, it seems a bit bruteforce and wondered if there is something much simpler than this.

Upvotes: 0

Views: 38

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

You can use match :

end_vec <- dat$index_vec[match(my_vec, dat$my_vec)]
end_vec <- end_vec[-1]
start_vec <- c(0, end_vec[-length(end_vec)] + 1)
start_vec
#[1]  0 14 52 65 86
end_vec
#[1] 13 51 64 85 97

Upvotes: 1

Related Questions