I am looking for the r equivalent of this simple code in python
mylist = []
for this in that:
df = 1
mylist.append(df)
basically just creating an empty list, and then adding the objects created within the loop to it.
I only saw R solutions where one has to specify the index of the new element (say mylist[[i]] <- df
), thus requiring to create an index i
in the loop.
Is there any simpler way than that to just append after the last element.
(Clarifying previous comment)
Use
$a [1] 0
$b [1] 1
$c [1] 2
$d [1] 3
Here's an example:
Now:
There is:
mylist <- c(mylist, df)
but that's usually not the recommended way in R. Depending on what you're trying to achieve,lapply()
is often a better option.This seems to me the faster solution.
There is a function called
append
:Note: Using
apply
functions instead of a for loop is better but it depends on the actual purpose of your loop.Answering OP's comment: About using
ggplot2
and saving plots to a list, something like this would be more efficient:Thanks to @Wen for sharing Comparison ofc()
andappend()
functions: