简体   繁体   中英

Function returning multiple values in R

Say I have a function

f <- function(){

  # do things

  return(list(zoo = x, vector = y, integer = z))
}

When I call this function using

result <- f()

Is there any way to call the return variables explicitly? Ie do I have to call it using

vara <- result$vara
varb <- result$varb
varc <- result$varc

Since if this function returns a lot of data types (whether it be data frames, zoo's, vectors, etc). The reason I dont want to bind into data frame is because not all variables are of the same length.

Use with or within

If the problem is just that you don't like typing result , then you can use with or within to access elements inside the list.

with(result, vara + varb * varc)

This is a good, standard way of doing things.

Use list2env

You could copy the variables from the list using list2env .

 list2env(result, parent.frame())

This is slightly risky because you have two copies of your variables which may introduce bugs. If you are including the code in a package, R CMD check will give you warnings about global variables.

Use attach

This is a really bad idea (don't do this).

attach is like a permanent version of with . If you

attach(result)

then you can access each element without the result$ prefix. But it will lead to many horrendous, obscure bugs in your code when an error gets thrown before you detach it, and then you attach it a second time and drown in a variable-scope-swamp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM