Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205372

Return a list with named elements from function

$
0
0

Question

I have a function like this:

myfunc <- function(x){

    a1 = 1
    a2 = c(2,4)
    a3 = data.frame(x = 1:10)
    ...
    an = 'str'
    res = list(a1 = a1,a2 = a2,..., an=an)
    return(res)
}

As we can see, I return my results with a named list. However, if the number of elements is large, I cannot type a_i = a_i one by one. I use the code snippet below to save half of my time(but I still need to type " around my elements' name, it's a waste of time):

res_short = sapply(c('a1','a2',...,'an'),FUN = function(x){list(get(x))})
return(res_short)

Note that there may not exist a pattern in my elements' name a1,a2,...,an, I just use a1,a2...,an to be simplified.

I think I return with a named list is good, since list can store different types of elements. Is there any other methods to write my function return? I want to be clear and time-saving!


Viewing all articles
Browse latest Browse all 205372

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>