Creating functions in Rstudio

0

From the following vector:

        Lagos <- c(41,72,8,93,4,37,73,190,45,22,19) 

I want to create a function that shows in the console the mean and standard deviation of that vector and that optionally can change the mean by the median

I have done the following:

     Lakers <- function(x){
                r <- mean(x) 
                s <- sd(x)
                t <- median(x)
                print(r)
                print(s)
                print(t)
                     }

The function responds correctly but the big problem is that I do not know how to indicate to that function that OPTIONALLY change the average by the median

If you could help me improve it please, I would appreciate it.

    
asked by polonio210 09.06.2017 в 16:29
source

1 answer

0

If you want the function to print either the average or the median. One possibility is to do this:

Lagos <- c(41,72,8,93,4,37,73,190,45,22,19) 

Lakers <- function(x, fun=mean){
    r <- fun(x) 
    s <- sd(x)
    print(r)
    print(s)
}
# La media la invoco de esta forma
Lakers(Lagos)
Lakers(Lagos, mean)

# La mediana  la invoco así
Lakers(Lagos, median)
    
answered by 09.06.2017 / 16:49
source