jakes
jakes

Reputation: 2085

Why ave results in error in unique.default?

x <- rnorm(100, 0, 10)
ave(x, cut(x, 10), mean)

Why exactly this returns the following error?

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

cut returns a factor of the same length as x and according to ave documentation:

... Grouping variables, typically factors, all of the same length as x.

Upvotes: 0

Views: 50

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Syntax for ave is

ave(x, ..., FUN = mean)

where ... is

Grouping variables, typically factors, all of the same length as x

which means you can have more than 1 grouping variable in ave. To apply the function in ave, you need to name the function with FUN explicitly.

Hence, do

ave(x, cut(x, 10), FUN = mean)

Moreover, the default function in ave is mean, so in this case you can directly do

ave(x, cut(x, 10))

Upvotes: 3

Related Questions