Robxaa798
Robxaa798

Reputation: 161

Function which calculates the mean

I have a problem with my function. I must create the function which return the values greater than mean. For example I have vector (3,6,3,12,4). Mean = 5,6 , so the function should return the values : 6,12. I try create this function but I lost. How I can fix this problem?

  for(i in 1:length(u))
  { 
    if(u[i] > mean(u))
      return(u[i])
    return()
  }
}

u <- c(3,6,3,12,4)
is.mean(u) ```

Upvotes: 0

Views: 48

Answers (1)

akrun
akrun

Reputation: 887531

We can do this easily without any loop

is.mean <- function(u) u[u>mean(u)]
is.mean(u)
#[1]  6 12

EDIT: Based on comments from @Abdessabour Mtk


Or using a for loop, create a NULL vector ('u1'), loop over the values of 'u', if the condition i.e. the value is greater than mean of the vector append the 'val' with the vector 'u1' and update by assigning (<-) to that vector

is.mean <- function(u) {
  u1 <- c()
  for(val in u) {
    if(val > mean(u)) u1 <- c(u1, val)
    }

 u1
 }

is.mean(u)
#[1]  6 12

data

u <- c(3,6,3,12,4)

Upvotes: 1

Related Questions