-2

I wrote a function in R using the code below: when I run it, an error message occurs: How does this happen?

columnmeans <- funtion(y) {
    nc <- ncol[y]
    means <- numeric(nc)
    for (i in 1:nc) {
        mean[i] <- mean(y[,i])
    }
    mean
}

I expect the function to work, but instead I received:

Error: unexpected '}' in "}"
zx8754
  • 52,746
  • 12
  • 114
  • 209

1 Answers1

1

You have a few errors in the code above. Here's a working version:

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

v <- data.frame(a=1:10, b=10:1)
columnmeans(v)
[1] 5.5 5.5

Your main issues are:

  • funtion should be function
  • ncol[y] should be ncol(y)
  • mean[i] should be means[i]
  • mean should be means
Stewart Macdonald
  • 2,062
  • 24
  • 27
  • 1
    Helped you out with an upvote @StewartMacdonald ;-) – doctorG Jul 04 '19 at 10:00
  • 6
    It is not about "want to see the world burn", but site rules, if it is typo, then it should be closed as such. Plus it is a duplicate, see my comment with links. – zx8754 Jul 04 '19 at 10:08