Search code examples
rfunctionstandardsmean

How to calculate the mean/sd of a vector without using the in-built R function?


this must be a very simple fix but I'm just struggling to figure out. I'm trying to write a function that will take a vector of numbers and calculate its mean and another function to calculate the sd. This is what I have now:

calc_avg <- function(vec){
  print(sum(vec)/length(vec))
}

list_d <- list(5,5)
calc_avg(list_d)

The error that's shown is this: Error in sum(vec) : invalid 'type' (list) of argument

In my head the function is very simple, but for whatever reason the sum function of R doesn't recognize the vec variable. If I just define it normally, it works fine.

Any help would be much appreciated, and yes, I'm 100% a noob when it comes to R.

Thanks.


Solution

  • it is a list, and sum requires a vector. According to ?sum

    ... - numeric or complex or logical vectors.

    So, unlist the list to convert it to vector

    calc_avg(unlist(list_d))
    #[1] 5