Dugong
Dugong

Reputation: 77

Sequential subtraction within a vector - in R, without using LOOP

Consider a list with length of n

a <- list(c(5, 41, 75, 158, 269, 432, 630, 901, 1534))

I am trying to make a sequential subtraction within this list. My goal is performing sequential subtraction by 1, making each elements 1 less than previous element, as the list is elongated.

As a result, I wish to have numbers in list as following:

a <- list(c(5, 41-1, 75-2, 158-3, 269-4, 432-5, 630-6, 901-7, 1534-8))

My 'pseudo-code' is as follows (which I cannot do in real-life R)

a[[1]][n] <- (a[[1]][n]-(n-1))

But again this does not work in real R.

Any recommendation in doing this?

Thank you!

Upvotes: 0

Views: 700

Answers (2)

akrun
akrun

Reputation: 887038

As it is a list of 1 vector, extract the vector with [[ and subtract from the sequence of 'a' (subtracted from 1)

a[[1]] <- a[[1]] - (seq_along(a[[1]]) - 1)   
a
#[[1]]
# [1]    5   40   73  155  265  427  624  894 1526

If it is a list with more than one vector use lapply

lapply(a, function(x) x - (seq_along(x) - 1))

Or with relist

relist(unlist(a) - (sequence(lengths(a))-1), skeleton = a)

Upvotes: 2

lapply(a,function(x,y)x-y,y=seq(from=0,length.out = length(a)))

Upvotes: 1

Related Questions