Home > Software design >  How to retrieve the previous list object when looping over a list in R
How to retrieve the previous list object when looping over a list in R

Time:06-11

Assume that I have a list

mylist <- list(5, 7, 9, 16)

And I want to make a function that calculates the difference in between a list object and the object before (i.e., in this case 7-5=2, 9-7=2, 16-9=7)

myfunction <- function(myvalue, myvalue_minus1){
  myvalue - myvalue_minus1
}

# Example
myresult <- myfunction(7, 5)
> myresult 
[1] 2

I want to count the difference in between all list objects, so I loop the function over the list.

However, how do I express that I want myvalue_minus1 always to be the previous value of the list (i.e., when value_i == [[2]], how do I get the loop to retrieve myvalue_minus1 == [[1]] ?

myvalue_list <- list()
for(value_i in 1:4){
  myvalue_list[[value_i]] <- myfunction(myvalue = value_i, myvalue_minus1)
}

# Desired output
> myvalue_list
[[1]]
[1] 5      # not sure if the first value should be 0 or 5

[[2]]
[1] 2

[[3]]
[1] 2

[[4]]
[1] 7

I've tried something like

myvalue_list <- list()
for(value_i in 1:4){
  myvalue_list[[value_i]] <- myfunction(myvalue = value_i, myvalue_minus1 = value_i[[i]] -1 ) # wrong
}

But this doesn't work. Any suggestions?

EDIT

The myfunction function is just to make an easily reproducible example, the function that I'm working with does something else. Thus, I'm only interested in answers that solve the question stated in the title.

EDIT 2 Added the desired output

CodePudding user response:

Try this function

myvalue_list <- list()
for(value_i in 2:4){
    myvalue_list[[value_i-1]] <- myfunction(myvalue = mylist[[value_i]],
    myvalue_minus1 = mylist[[value_i-1]])
}

myvalue_list

#> [[1]]
#> [1] 2
#> 
#> [[2]]
#> [1] 2
#> 
#> [[3]]
#> [1] 7
  • Related