Question

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
Was it helpful?

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

OTHER TIPS

The best solution here is to use lapply as @Jilber.

In case you want to know how to append a list:

result = list()             
for(i in c(1:3))
{
  result[[i]]<- seq(df [1,i], df [2,i], df [3,i])
}
result

lapply is the way to go. Here is another approach that uses the fact that a data.frame is simply a list.

lapply(df, function(x) do.call(seq,as.list(x)))
# $A
# [1]   0   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100
#
# $B
# [1]   0  10  20  30  40  50  60  70  80  90 100
# 
# $C
# [1]   0  25  50  75 100
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top