Skip to content
Back to formatted view

Raw Message

Message-ID: <4069F67C506548AA93EFD9890CE6ACA7@TCPC000>
Date: 2008-12-22T15:38:54Z
From: Mark Heckmann
Subject: imputing the numerical columns of a dataframe, returning the rest unchanged

Hi R-experts,

how can I apply a function to each numeric column of a data frame and return
the whole data frame with changes in numeric columns only?
In my case I want to do a median imputation of the numeric columns and
retain the other columns. My dataframe (DF) contains factors, characters and
numerics. 

I tried the following but that does not work:

foo <- function(x){
  if(is.numeric(x)==TRUE) return(impute(x))
  else(return(x))
}

sapply(DF, foo)

      day version     ID     V1     V2  V3 
  [1,] "4" "A"       "1a"     "1"   "5"  "5" 
  [2,] "4" "A"       "2a"     "2"   "3"  "5" 
  [3,] "4" "B"       "3a"     "3"   "5"  "5" 

All the variables are coerced to characters now ("day" and "version" were
factors, "id" a character). I only want imputations on the numerics, but the
rest to be returned unchanged.

Is there a function available. If not, how can I do it?

TIA and merry x-mas,
Mark