Return various data frames to a function - R

Is it possible to return 4 different data frames from one function?

Scenario:

I am trying to read a file, parse it and return some parts of the file.

My function looks something like this:

parseFile <- function(file){ carFile <- read.table(file, header=TRUE, sep="\t") carNames <- carFile[1,] carYear <- colnames(carFile) return(list(carFile,carNames,carYear)) } 

I do not want to use a list (carFile, carNames, carYear). Is there a way to return 3 frames of data without returning them in the list in the first place?

+6
source share
2 answers

R does not support multiple return values. You want to do something like:

 foo = function(x,y){return(x+y,xy)} plus,minus = foo(10,4) 

Yes? Well, you can’t. You receive an error message that R cannot return multiple values.

You have already found a solution - put them in a list, and then get data frames from the list. This is effective - there is no conversion or copying of data frames from one memory block to another.

This is also logical, the return from the function should conceptually be a single object with some value that is passed to any function that calls it. This value is also better conveyed if you name the return values ​​of a list.

You can use the technique to create multiple objects in a calling environment, but when you do this, kittens die.

Note in your example, carYear not a data frame β€” its character vector of column names.

+20
source

There are other ways to do this if you really really want to, in R.

 assign('carFile',carFile,envir=parent.frame()) 

If you use this, then a carFile will be created in the calling environment. As Spacedman said, you can return only one thing from your function, and the pure solution is to go to the list.

In addition, my personal opinion is that if you find yourself in a situation where it seems to you that you need to return several data cells with one function or do something that no one has ever done before, you should really reconsider your approach . In most cases, you can find a cleaner solution with an additional function, perhaps with a recommended one (i.e. a list).

In other words,

 envir=parent.frame() 

will do the job, but as SpacedMan said

when you do this, kittens die

+3
source

All Articles