Help fixing a function

Hello everyone. This is a cryfor help regarding my Homework.
I need help fixing a function I wrote because it is not doing the purpose I wrote it for.

The assignment was to write a function (you can name it however you want) and it suposed goes like this:

MyMean <- function (x, na.rm = FALSE)

x is a numeric not empty vector that could have NA values.
na.rm is a Boolean value that his default is FALSE.
Term 1: If na.rm== FALSE and there are missing values at X, the function should return NA
Term 2: If na.rm == FALSE and there are no missing values, the function should calculate the mean of the numeric vector mathematical organs.
Term 3: if na.rm == TRUE, and their are missing organs, the function should return the mean of the vector mathematical organs without the missing one.

This is what I wrote:
myMean <- function(x, na.rm=FALSE){
for(ind in 1:length(x)){
if([ind]== TRUE & na.rm == FALSE)){
}else if([ind]== FALSE & na.rm == FALSE)){
}else if([ind]== TRUE & na.rm == TRUE)){
new.Sum <- 0
Deacrese <- 0
for(ind in 1:length(x)){
if([ind]== FALSE)){
new.Sum <- new.Sum + x[ind]
Deacrese <- Deacrese + 1

Thank you for the help and God Bless You All

As a first thing note that


is inside your for loop. Suppose the first element of x has a valid number, the function then returns immediately even though later elements might be an NA.


try to think logically about the problem. You have to recreate the base mean() function and return NA if there are any missing values. So all you have to do is implement two checks for validity as well as the actual calculations. You might want to use this pseudo code to work with:

myMean <- function(x, na.rm = FALSE){
  if(condition regarding NA and na.rm = FALSE) return(NA_integer_)
  if(condition regarding the numeric class requirement) stop('Non numeric vector')
  if(condition if NA are present but na.rm = TRUE) x <- x[!]

  sum(x) / length(x)

The second condition is optional, since trying to calculate the sum of characters will give an error anyways

kind regards

1 Like

thank you I will try it

thank you so much, amazing !! it is working.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.