Colin Menezes
Colin Menezes

Reputation: 1

Invalid length error for beginner

I have checked previous questions but couldn't find an answer

 columnmean<-function(y){
    n<-ncol(y)
    means<-numeric(n)
    for(i in 1:n){
        means[i]<-mean(y[,i])
    }
    means}

I simply cannot understand the error, even the code seems right. Also, i get some dimension error if i input the value of n in this line

 means[i]<-mean(y[,i])

Upvotes: 0

Views: 1947

Answers (1)

jogo
jogo

Reputation: 12559

Here is a reproduction of the error:

columnmean<-function(y){
  n <- ncol(y)
  means <- numeric(n)
  for(i in 1:n) {
    means[i] <- mean(y[,i])
  }
  means
}
columnmean(1:10)

If y is a vector the result of ncol(y) is NULL. The following calculation in your function raises the error.
Also colMeans(1:10) will cause an error (another error because of better internal checking of the argument).

So, your code is correct for twodimensional data, e.g.:

columnmean(BOD)
# [1]  3.666667 14.833333

The error depends from y (y with only one dimension, i.e. a vector ~~> error).

Upvotes: 2

Related Questions