[R] Help with loop

paulalou pls28 at medschl.cam.ac.uk
Wed Jul 11 16:11:22 CEST 2012


Hi,

I have two dataframes:

The first, df1, contains some missing data:

   cola colb colc cold cole
1    NA    5    9   NA   17
2    NA    6   NA   14   NA
3     3    NA   11   15   19
4     4    8   12   NA   20

The second, df2, contains the following:

  cola colb colc cold cole
1  1.4  0.8 0.02  1.6  0.6

I'm wanting all missing data in df1$cola to be replaced by the value of
df2$cola. Then the missing data in df1$colb to be replaced with the
corresponding value in df2$colb etc.

I can get this to work column by column with single input lines but as my
original dataset is a lot larger I'm wanting a create a loop but can't work
out how.

The single line command is:

 df1$cola[is.na(df1$cola)]<-df2$cola

I've tried a replace function within a loop but get error messages:

list<-colnames(df1)

for (i in list) {
 r<-replace(df1$i,df1$i[is.na(df1$i)],df2$i)
 }


with error messages of:

Warning messages:
1: In is.na(mymat$snp) :
  is.na() applied to non-(list or vector) of type 'NULL'

Can anyone help me with this?

Thanks 

--
View this message in context: http://r.789695.n4.nabble.com/Help-with-loop-tp4636140.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list