4

Let's say I have a vector of prices:

foo <- c(102.25,102.87,102.25,100.87,103.44,103.87,103.00)

I want to get the percent change from x periods ago and, say, store it into another vector that I'll call log_returns. I can't bind vectors foo and log_returns into a data.frame because the vectors are not the same length. So I want to be able to append NA's to log_returns so I can put them in a data.frame. I figured out one way to append an NA at the end of the vector:

log_returns <- append((diff(log(foo), lag = 1)),NA,after=length(foo)) 

But that only helps if I'm looking at percent change 1 period before. I'm looking for a way to fill in NA's no matter how many lags I throw in so that the percent change vector is equal in length to the foo vector

Any help would be much appreciated!

2
  • You can store in a list instead Commented Feb 5, 2016 at 1:59
  • 6
    the answer below is nice, but more generally if you have a list of unequal length vectors, you can do something like l <- list(1, 1:2, 1:5); data.frame(lapply(l, `length<-`, max(lengths(l)))) Commented Feb 5, 2016 at 2:05

1 Answer 1

3

You could use your own modification of diff:

mydiff <- function(data, diff){
  c(diff(data, lag = diff), rep(NA, diff))
}

mydiff(foo, 1)
[1]  0.62 -0.62 -1.38  2.57  0.43 -0.87    NA

data.frame(foo = foo,  diff = mydiff(foo, 3))

     foo  diff
1 102.25 -1.38
2 102.87  0.57
3 102.25  1.62
4 100.87  2.13
5 103.44    NA
6 103.87    NA
7 103.00    NA
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.