Babble
Babble

Reputation: 11

I need to create a function in R for mean without using the base functions mean() or sum()

I know this is a pretty simple question but I am new to R and am having serious trouble coming up with a mean function that does not include "sum()". Can anyone help with this? Here is what I have:

newmean <- function(x)
  {mn = sum(x)/length(x)}
simple <- c(1:9)
print(newmean(simple))

But I have to replace the "sum()" with something else. What should I do?

Upvotes: 1

Views: 279

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 102309

You can try crossprod + rep like below

newmean <- function(x) c(crossprod(x,rep(1,length(x)))/length(x))

and you will see

> newmean(seq(10))
[1] 5.5

Upvotes: 0

Leonardo
Leonardo

Reputation: 2485

A very basic approach:

newmean <- function(x) {
  sum_ <- 0
  for (i in 1:length(x)) {
    sum_ <- sum_ + x[i] 
  }
  sum_ / length(x)
}

newmean(1:10)
5.5

Upvotes: 4

tmfmnk
tmfmnk

Reputation: 40141

One option could be:

newmean <- function(x) Reduce(`+`, x)/length(x)

Upvotes: 3

Related Questions