how to use a dataframe returned by r function

I defined a R function, and want this function to return 2 dataframes, so I can use this dataframe outside the R function. However, if fails to return the two data frames, but it can print out the data frame in R.

Here are my code,

useDataFrame <- function(tab1,tab2){
  
d6 <- read.table(paste0("/Users/limin/Desktop/cnr_cns/", tab1) , header = T)
seg <- read.table(paste0("/Users/limin/Desktop/cnr_cns/", tab2) , header = T)
return(d6)
return(seg)
}
useDataFrame("A01.cnr","A02.cns")
df1 <- d6
df2 <- seg

Could anyone suggests what part of my code went wrong? How do I modify the code, so I can use the dataframe returned by R function?

Your helps are greatly appriciated.

Best,

A function can only return one object, though that object can be a list containing many elements.

useDataFrame <- function(tab1,tab2){
  
d6 <- read.table(paste0("/Users/limin/Desktop/cnr_cns/", tab1) , header = T)
seg <- read.table(paste0("/Users/limin/Desktop/cnr_cns/", tab2) , header = T)
return(list(d6, seg))
}

DF_list <- useDataFrame("A01.cnr","A02.cns")
df1 <- DF_list[[1]]
df2 <- DF_list[[2]]

A function can only return one object, so if you want to return two make a list containing both and return that list. Something like:

returnedList <- list(df1, df6)
return(returnedList)
r<-useDataFrame(tab1,tab2)
r$df1
r$df6

Hi FJCC,

Thanks for the suggestion. It works.

For return one object in the R function, the following code works. Does that mean the r return() code is not required in a function. As long as we save the output when we call the function?

useDataFrame <- function(tab1,tab2){
d6 <- read.table(paste0("/Users/limin/Desktop/cnr_cns/", tab1) , header = T)
}
DF <- useDataFrame("AJ-06_T.deduplicated.realign.cnr")
f <- DF

The following code not working:

useDataFrame <- function(tab1,tab2){
d6 <- read.table(paste0("/Users/limin/Desktop/cnr_cns/", tab1) , header = T)
return(d6)
}
useDataFrame("AJ-06_T.deduplicated.realign.cnr")
f <- d6

Screen Shot 2021-11-16 at 1.59.53 PM

Therefore, my understanding is: no matter how many objects we want an R function to return, first we need to save the output of calling a function. And r return() is not required.

Is my understanding correct?

Best,

LC

Hi startz,

Thank you so much. That helps a lot.

Best,

LC

The return() function is not required. The rule is

If the end of a function is reached without calling return, the value of the last evaluated expression is returned.

Yes, you must assign the value returned by the function to a variable if you want to use that value later in the code.

Really appreciate your answer!
You clarified all my confusion.

Have a wonderful day.

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it: