0

I was trying to address the missing values in R through the following code

  {ds$bmi=ifelse(is.na(ds$bmi), ave(ds$bmi, Fun=function(x) mean(y,na.rm=TRUE)),ds$bmi)}   

it is giving following error

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

Please help how to address this error

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
user3767287
  • 3
  • 1
  • 2
  • 1
    For a start, you have `function(x)` but then use `y` as your variable! – Andrew Gustar Mar 12 '18 at 18:56
  • 2
    Not sure what are you trying to achieve. You should provide minimal reproducible example data. e.g. The details of `ds$bmi` is not know. Have a look at https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example. It will help you in asking questions in a better way. – MKR Mar 12 '18 at 19:07
  • Thanks got it. this error was due to y only – user3767287 Mar 13 '18 at 17:09
  • It's not `Fun=function(x)`, it's `FUN`, R is case sensitive. – Rui Barradas Mar 14 '18 at 17:03

1 Answers1

0

Here 'ave' doesn't have any of the "Grouping variables, typically factors, all of the same length as x." as described in ?ave (the ... args).

If the goal is to replace NA's with the mean of bmi, maybe just straight up mean is what you want?

hm_rows=10;
ds=data.frame(bmi=runif(hm_rows,0,10))
ds[c(1,2,4,6),"bmi"] <- NA
{ds$bmi=ifelse(is.na(ds$bmi), mean(ds$bmi,na.rm=TRUE),ds$bmi)}
steveLangsford
  • 646
  • 5
  • 9