r - Impute missing values with the average of the remainder -


i have data frame of form:

weight  day     hour na      m       0 na      m       1 2       m       2 1       m       3 4       t       0 5       t       1 na      t       2 2       t       3 3       w       0 3       w       1 1       w       2 na      w       3 

for given na value in weight, want replace average of non-na values having same value hour. example, first value in weight na. hour value 0, want average other weights hour 0 (those values being 4 , 3). want replace na computed average (3.5).

as r beginner, i'd see clear, multistep process this. (i'm posing learning exercise rather specific "solve problem" type question. i'm not interested in can in fewest characters.)

you can use ave such operations.

dat$weight <-  ave(dat$weight,dat$hour,fun=function(x){   mm <- mean(x,na.rm=true)   ifelse(is.na(x),mm,x) }) 
  • you apply function group of hours.
  • for each group compute mean wuthout missing values.
  • you assign mean if value missing value otherwise keep origin value.
  • you replace weight vector new created vector.

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -