returning different data frames in a function - R

dataframe, function, r

Solution

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

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

yeah? Well, you can't. You get an error that R cannot return multiple values.

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

This is also logical, the return from a function should conceptually be a single entity with some meaning that is transferred to whatever function is calling it. This meaning is also better conveyed if you name the returned values of the list.

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

Note in your example `carYear` isn't a data frame - its a character vector of column names.

Problem

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 don't want to have to use list(carFile,carNames,carYear). Is there a way return the 3 data frames without returning them in a list first?

Original source

Related problems