Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R error in unique.default(x) unique() applies only to vectors

Tags:

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?

like image 854
time Avatar asked May 22 '13 00:05

time


1 Answers

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.)

like image 68
flodel Avatar answered Sep 17 '22 14:09

flodel