Search code examples
rlistfunctionseq

Storing function output in a list in R


I have the following data frame

df <- data.frame(A = c(0,100,5), B = c(0,100,10), C = c(0,100,25)

which I use with this function

for(i in c(1:3))) 
{seq(df [1,i], df [2,i], df [3,i])
}

I need store the output but so far I only managed to print the results using

{y<-seq(df [1,i], df [2,i], df [3,i])
print(y)}

Instead I would like to store these output in a list to obtain something like

[[1]]
[1]   0   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100

[[2]]
[1]   0  10  20  30  40  50  60  70  80  90 100

[[3]]
[1]   0  25  50  30  100

Solution

  • Use lapply instead of for loop

    > lapply(1:3, function(i) seq(df[1,i], df[2,i], df[3,i]))
    [[1]]
     [1]   0   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100
    
    [[2]]
     [1]   0  10  20  30  40  50  60  70  80  90 100
    
    [[3]]
    [1]   0  25  50  75 100