-1

I really don't know how R functions works! It doesn't work like matlab that we can return and also call many objects of our function?

I'm writting a function inwhich I need to have more than one outcome, but it returns me just one. I wonder how the R programmers can write such functions. For example: sort

s<-sort(c(10:3, 2:12), method = "shell", index.return = TRUE)
s$x
s$ix

As we see we can call two external objects(x: sorted vector , ix: index of the sorted vector)

Also I can't understand when I want to see inside the written function in R. for example for a simple function like "mean" we have:

> mean
function (x, ...) 
UseMethod("mean")
<bytecode: 0x0000000017c57d28>
<environment: namespace:base>

Thanks en advance

Nafis

  • 1
    Your first question: Those are not external objects. `s` is a `list` object. See the R tutorial. Your second question: mean is an S3 generic. The bytecode is the compiler bytecode. The environment is the namespace of the base package. But you really should get an introductory course on R before you go any further. There's some great free ones, eg on datacamp.com – Joris Meys Jun 14 '17 at 16:18
  • Like @Joris Meys said. `sort` returns a `list`. which in this case contains two vectors `x` and `ix`. If you would like similar functionality for your own function, you would only need to save your objects as items within a list and then return the list from your function. – Matt Jewett Jun 14 '17 at 16:22
  • Your second question is a duplicate of [this](https://stackoverflow.com/q/19226816/324364). – joran Jun 14 '17 at 16:31

1 Answers1

1

Here is an example of a simple function, showing how to return a list that contains multiple items.

# Create the function
my.function <- function(){

  # Create some vectors
  obj1 <- c("Character", "Vector", "One")
  obj2 <- c("Character", "Vector", "Two")
  obj3 <- c("Character", "Vector", "Three")

  # Create empty list
  my.list <- list()

  # Assign objects to list
  my.list$o1 <- obj1
  my.list$o2 <- obj2
  my.list$o3 <- obj3

  # Return the list
  return(my.list)
}

# Call the function
list.from.function <- my.function()

# Inspect a specific item
list.from.function$o1
Matt Jewett
  • 3,249
  • 1
  • 14
  • 21