26

I created a dataset named state from the built-in matrix state.x77 with two continuous variables (Population and Income) and two factor variables (region and area).

I computed mean income by region using tapply(), by(), aggregate(), and ave() to see the format of the returned object.

But the call to ave() is giving the error

Error in unique.default(x) : unique() applies only to vectors

The code is:

## Mean income by region
tapply(state$inc, state$region, mean)
# Northeast         South North Central          West 
# 4570.222       4011.938      4611.083      4702.615 

by(state$inc, state$region, mean)
# state$region: Northeast
#
# [1] 4570.222
# [...]

aggregate(state$inc, list(state$region), mean)
#
#         Group.1        x
# 1     Northeast 4570.222
# 2         South 4011.938
# 3 North Central 4611.083
# 4          West 4702.615

ave(state$inc, state$region, mean)
# Error in unique.default(x) : unique() applies only to vectors

Why is the error occurring? How can I prevent it?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
time
  • 921
  • 3
  • 12
  • 15

2 Answers2

32

This is a very common mistake, you need to use the named argument FUN:

ave(state$inc, state$region, FUN = mean)

otherwise mean will be interpreted as another grouping variable (part of the ... argument to ave.)

flodel
  • 87,577
  • 21
  • 185
  • 223
  • Thank you very much. the error has been prevented. But i also didn't use FUN in tapply(), by(), aggregate() command. then why those didn't occur error? – time May 22 '13 at 00:58
  • 2
    It is because inside `ave`'s synopsis (argument list), `FUN` comes **after** `...` so if you do not pass it specifically with `FUN=`, then R will think it is part of the `...` argument and use the default (`mean`) for `FUN`. – flodel May 22 '13 at 01:01
0

You may check whether the R use the correct function, I tried to specify the function just like below example. enrichplot::dotplot(kegg) That may help you. ps.I am a beginner of R script.

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 03 '22 at 14:21