Patrick Williams
Patrick Williams

Reputation: 704

R seq function between item 1 and 2, then between 2 and 3 of a vector

I have a vector c(5, 10, 15) and would like to use something like the seq function to created a new vector: 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15. This is how I would do it now, but it seems ineloquent at best. In the final (functional) form, I would need to increment by any given number, not necessarily units of 1.

original_vec <- c(5, 10, 15)
new_vec <- unique(c(seq(original_vec[1],original_vec[2],1),seq(original_vec[2],original_vec[3],1)))
> new_vec
[1]  5  6  7  8  9 10 11 12 13 14 15

Is there a way (I'm sure there is!) to use an apply or similar function to apply a sequence across multiple items in a vector, also without repeating the number in the middle (in the case above, 10 would be repeated, if not for the unique function call.

Edit: Some other possible scenarios might include changing c(1,5,7,10,12) to 1,1.5,2,2.5 ... 10, 10.5, 11, 11.5, 12, or c(1,7,4) where the price increases and then decreases by an interval.

The answer may be totally obvious and I just can't quite figure it out. I have looked at manuals and conducted searched for the answer already. Thank you!

Upvotes: 0

Views: 489

Answers (1)

Patrick Williams
Patrick Williams

Reputation: 704

While this isn't the answer to my original question, after discussing with my colleague, we don't have cases where seq(min(original_vec), max(original_vec), by=0.5), wouldn't work, so that's the simplest answer.

However, a more generalized answer might be:

interval = 1
seq(original_vec[1], original_vec[length(original_vec)], by = interval)

Edit: Just thought I'd go ahead and include the finished product, which includes the seq value in a larger context and work for increasing values AND for cases where values change direction. The use case is the linear interpolation of utilities, given original prices and utilities.

orig_price <- c(2,4,6)
orig_utils <- c(2,1,-3)

utility.expansion = function(x, y, by=1){
  #x = original price, y = original utilities
  require(zoo)
  new_price <- seq(x[1],x[length(x)],by)
  temp_ind <- new_price %in% x
  new_utils <- rep(NA,length(new_price))
  new_utils[temp_ind] <- y
  new_utils <- na.approx(new_utils)
  return(list("new price"=new_price,"new utilities"=new_utils))
}

Upvotes: 1

Related Questions