Reputation: 83
I have a vector in r say
a = log10(1:1000) + rnorm(1000)
I want to convert this data set based on a parameter given say
n = 10
A function say
b = function(a,x){...........................}
d = b(a,x)
such that my data should be converted to
d =
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
a2 a3 a4 a5 a6 a7 a8 a9 a10 a11
..................................
.................................
a990 a991 a992 a993 a994 a995 a996 a997 a998 a999
a991 a992 a993 a994 a995 a996 a997 a998 a999 a1000
Upvotes: 0
Views: 45
Reputation: 93803
A bit simpler using ?embed
:
embed(a,n)[,n:1]
It doesn't have the same names, and returns a matrix, but otherwise it is identical to your longer result:
identical( embed(a,n)[,n:1], unname(as.matrix(b)) )
#[1] TRUE
Upvotes: 1
Reputation: 3116
Try this:
b= function(a,n){
lst=sapply(1:(length(a)-n),function(t,a,n){a[t:(n+t-1)]},a,n,simplify = F)
Reduce(function(x,y){rbind(x,y)},lst)
}
Upvotes: 1
Reputation: 83
a = log10(1:1000)+rnorm(1000,0,2)
n = 10
b = matrix(rep(a,n),nrow=length(a))
for(i in 1:n){
b[1:length(a),i] = c(rep(NA,n-i),b[1:(length(a)-n+i),i])
}
b = na.omit(b)
b = as.data.frame(b)
Upvotes: 0