See the FAQ: How to do a minimal reproducible example reprex
for beginners. Without representative data only general answers can be given.
The way to think about functions in R
is like the old commercial
What happens in Las Vegas stays in Las Vegas
In the for
loop temp_list
is getting clobbered each iteration, and only the last through the gate survives to tell the tale. To escape everything, each iteration must be saved to an object that will persist when the function finishes.
The most straightforward way to do this is to pre-allocate a receiver object in the global environment. Here's a silly example
holder <- vector(mode = "character", length = 26)
for(i in seq_along(LETTERS)) holder[i] = tolower(LETTERS[i])
holder
#> [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
#> [20] "t" "u" "v" "w" "x" "y" "z"
(Silly, because the way to do this if we just wanted to lowercase the uppercase letters would be tolower(LETTERS)
.)
Think of this as school algebra f(x) = y. x is what is to hand, y is what is required and f is a function, which may be composite to transform one to the other.
In the example x is an object containing the uppercase Roman letters and y contains the corresponding lowercase. As we want to create y piecewise, we create holder
as a receiver object to save intermediate results each time through the loop. Then f is a composite of for
seq_along
and tolower
, along with the subset operator [
.
for
makes it piecewise, seq_along
allows sizing the number of iterations to the size of the object to be iterated over, instead of in 1:26
(always better not to hardwire) and tolower
does the transformation of upper to lower on each element.
If this makes sense, apply f(x) to your data.