Ocean
Ocean

Reputation: 81

Creating multiple new vectors from original vector

I have a vector d and I create new vector from d such that new vector contain every mth element of d:

v<-d[seq(1,length(d),m)]

the next step I would like to calculate the sum

s<-sum(abs(v[1:(length(v)-1)]-v[2:length(v)]))

It would be no problem if I do this with few values of m. However, if I have a more than 50 values for m, doing this one by one will not be a desired way. I think of generalising the way of creating v corresponding with different value of m. The following is the code that I came up with:

d1<-rnorm(20)
m<-seq(1,10,1)
v<-matrix(rep(0,length(d1)*lenght(m)),nrow=length(m))
for (i in 1:length(m)){v[i,]<-d1[seq(1,length(d1),m[i])]}

but when I run the code, the following error appear:

Error in v[i, ] <- d1[seq(1, length(d1), m[i])] : 
number of items to replace is not a multiple of replacement length

So I tried another way:

v<-rep(0,length(d1))
for (i in 1:length(m)){v<-d1[seq(1,length(d1),m[i])]}

but this code only give me the value of v at m=m[length(m)], not all vectors v corresponding with m[1]to m[length(m)]. Could anyone suggest me a function/a way to solve this?

Many thanks in advance

Upvotes: 0

Views: 90

Answers (2)

IRTFM
IRTFM

Reputation: 263342

I think you are perhaps trying to do this:

for (i in 1:length(m)){assign(paste0("v",i), d1[ seq(1, length(d1), m[i])] }

My advice ... don't. You should be learning to build lists:

vres <- lapply( seq_along(m) , 
                  function(i) d1[ seq(1, length(d1), m[i])] )

Upvotes: 1

Richard Herron
Richard Herron

Reputation: 10102

I try to avoid for loops and use the apply family instead. Your function generates a bunch of vectors of different lengths, which I combine into a list. Both data frames and matrices have to be even, or non-ragged, so I have to pad your vectors with NAs, then I column bind them.

Does this work?

set.seed(2001)
d1 <- rnorm(20)
m <- seq(1, 10, 1)
ragged <- lapply(m, FUN=function(x) d1[seq(1, length(d1), x)]) 
maximum <- max(sapply(ragged, length))
even <- lapply(ragged, FUN=function(x) {
               xx <- rep(NA, maximum)
               xx[seq(length(x))] <- x
               xx
})
even1 <- do.call(cbind, even)

Upvotes: 1

Related Questions