user3440244
user3440244

Reputation: 371

returned objects within a list while keeping the original data structure in R

In R, I need to return two objects from a function:

myfunction()
{
 a.data.frame <- read.csv(file = input.file, header = TRUE, sep = ",", dec = ".")
 index.hash <- get_indices_function(colnames(a.data.frame))

 alist <- list("a.data.frame" = a.data.frame, "index.hash" = index.hash)

 return(alist)
}

But, the returned objects from myfunction all become list not data.frame and hash.

Any help would be appreciated.

Upvotes: 0

Views: 59

Answers (2)

Daniel
Daniel

Reputation: 7832

You can use a structure.

return (structure(class = "myclass",
                   list(data = daza.frame,
                        type = anytype,
                        page.content = page.content.as.string.vector,
                        knitr = knitr)))

Than you can access your data with

values <- my function(...)
values$data
values$type
values$page.content
values$knitr

and so on.

A working example from my package:

sju.table.values <- function(tab, digits=2) {
  if (class(tab)!="ftable") tab <- ftable(tab)
  tab.cell <- round(100*prop.table(tab),digits)
  tab.row <- round(100*prop.table(tab,1),digits)
  tab.col <- round(100*prop.table(tab,2),digits)
  tab.expected <- as.table(round(as.array(margin.table(tab,1)) %*% t(as.array(margin.table(tab,2))) / margin.table(tab)))
  # -------------------------------------
  # return results
  # -------------------------------------
  invisible (structure(class = "sjutablevalues",
                       list(cell = tab.cell,
                            row = tab.row,
                            col = tab.col,
                            expected = tab.expected)))
}

tab <- table(sample(1:2, 30, TRUE), sample(1:3, 30, TRUE))
# show expected values
sju.table.values(tab)$expected
# show cell percentages
sju.table.values(tab)$cell

Upvotes: 1

user3471268
user3471268

Reputation:

You can only return one object from an R function; this is consistent with..pretty much every other language I've used. However, you'll note that the objects retain their original structure within the list - so alist[[1]] and alist[[2]] should be the data frame and hash respectively, and are structured as data frames and hashes. Once you've returned them from the function, you can split them out into unique objects if you want :).

Upvotes: 2

Related Questions