Returning multiple objects in an R function
Unlike many other languages, R functions don't return multiple objects in the strict sense. The most general way to handle this is to return a list
object. So if you have an integer foo
and a vector of strings bar
in your function, you could create a list that combines these items:
foo <- 12
bar <- c("a", "b", "e")
newList <- list("integer" = foo, "names" = bar)
Then return
this list.
After calling your function, you can then access each of these with newList$integer
or newList$names
.
Other object types might work better for various purposes, but the list
object is a good way to get started.
Return multiple values from a function
In R you can only return one object. You could put the three values in a list or a vector and then return that list or vector.
How to assign from a function which returns more than one value?
(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...]
like this:
library(gsubfn) # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()
If you only need the first or second component these all work too:
list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()
(Of course, if you only needed one value then functionReturningTwoValues()[[1]]
or functionReturningTwoValues()[[2]]
would be sufficient.)
See the cited r-help thread for more examples.
(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with
:
myfun <- function() list(a = 1, b = 2)
list[a, b] <- myfun()
a + b
# same
with(myfun(), a + b)
(3) attach Another alternative is attach:
attach(myfun())
a + b
ADDED: with
and attach
How to return multiple objects from R script executed in Python
Q.1: How do I pull the various elements from the result?
Ans.1: After you run your R script:
test = ro.r(your_R_script)
You can use this code to print out all the names
and values
in the test
object.
# iterate on names and values
# be careful output is v long
for n,v in test.items():
print(n)
print(v)
To list all available names
, run this code:
test.names
The output:
StrVector with 12 elements.
'coeffici... 'residuals' 'effects' 'rank' ... 'xlevels' 'call' 'terms' 'model'
To print values of the 'residuals', run this:
test[test.names.index('residuals')]
Q.2: What happens to df?
Ans.2: It is still available in R environment until you delete it. You can run simple R code to check:
ro.r('''
# View dataframe
df
''')
Q.3: Is there a much much better way to do this?
Ans.3: (No answer.)
How to return multiple values from a function in R for each iteration of a loop? Simple life history simulation
You could return a dataframe from getMC
function. Also instead of relying on vectors in global environment (walkpop
, cathpop
etc) pass them into the function.
getMC <- function(data, ref_data){
walkpop = ref_data$walkpop*data$walksurv
cathpop = ref_data$cathpop*data$cathsurv
abovepop = ref_data$abovepop*data$abovesurv
walkpop_pre_trans = walkpop
walkpop = walkpop - walkpop_pre_trans*data$walktrans_out_C -
walkpop_pre_trans*data$walktrans_out_A
return(data.frame(walkpop, cathpop, abovepop))
}
walkpop = 10000
abovepop = 1000
cathpop = 100
ref_data <- data.frame(walkpop, abovepop, cathpop)
totallist = vector('list', 2)
for (i in 1:2) {
ref_data <- getMC(data, ref_data)
totallist[[i]] <- ref_data
}
Checking the output.
lapply(totallist, head)
#[[1]]
# walkpop cathpop abovepop
#1 8905.669 80 833.4328
#2 9327.844 80 833.4328
#3 8905.669 80 970.8581
#4 9327.844 80 970.8581
#5 8696.702 80 833.4328
#6 9108.971 80 833.4328
#[[2]]
# walkpop cathpop abovepop
#1 7931.094 64 694.6102
#2 8700.868 64 694.6102
#3 7931.094 64 942.5655
#4 8700.868 64 942.5655
#5 7563.262 64 694.6102
#6 8297.335 64 694.6102
R return multiple data.tables from function
return(list(train = data.table(train), test =data.table(test)))
train=tt_list$train
here:Returning multiple objects in an R function
and here:
How to assign from a function which returns more than one value?
How to handle multiple outputs in an R function?
You cannot return multiple times in R function. After encountering the first return
it doesn't go any further.
Return lists instead.
mycustomfunction <- function (input1,input2,input3) {
output1 = input1 + input2
output2 = input3
return(list(output1 = output1, output2 = output2))
}
result <- mycustomfunction(10,35,3)
result
#$output1
#[1] 45
#$output2
#[1] 3
You can access individual values using $
operator.
result$output1
#[1] 45
result$output2
#[1] 3
Reuse multiple objects created in a function
I'd use a simple return()
with a list()
or c()
:
test1 <- function(x){
y <- x + 1
z <- x * 2 # if you don't use return these two won't leave test1
return(list(y=y, z=z)) # equivalent without return() is list(y=y, z=z)
#or: list(y=y, z=z)
}
test2 <- function(...){
ret1 <- test1(x)
print(ret1$y * ret1$z)
#or: return(ret1$y * ret1$z)
}
Note that the use of return()
is not necessary, since the last object not assigned in a function is returned automatically.
The use of return()
may help with readability though.
A read about return()
.
How to return list of multiple objects from a function in R?
After some trial and error I found a simple solution - I'll post here in case there is interest:
f <- (function(a,b)
{
trainy <- c(log(a$y))
trainx <- data.matrix(a)
testx <- data.matrix(b)
list_i <<- list(trainy, testx)
})
fit <- mapply(f,train_subset,test_subset)
where the object fit
is a 2x3 matrix containing the trainy and testx output.
Related Topics
Read Multiple CSV Files into Separate Data Frames
Read All Worksheets in an Excel Workbook into an R List With Data.Frames
Levels≪-'( What Sorcery Is This
Applying a Function to Every Row of a Table Using Dplyr
What Ways Are There to Edit a Function in R
Plot Multiple Lines in One Graph
How to Read in Numbers With a Comma as Decimal Separator
Get "Embedded Nul(S) Found in Input" When Reading a CSV Using Read.Csv()
Method to Extract Stat_Smooth Line Fit
How to See the Source Code of R .Internal or .Primitive Function
Create a Group Number For Each Consecutive Sequence
Intelligent Point Label Placement in R
Geom_Rect and Alpha - Does This Work With Hard Coded Values
How to Create an R Function Programmatically