3

Again I need your help for a maybe easy question that is not clear for a starter R user.

I need to manipulate a dataframe to substitute NA values by "realistic" ones to feed another application.

The data frame contains values of -3.0 that was the flag for non valid values in the original data base. What I need is to replace all the -3.0 values by data coming from another data frame, or maybe to interpolate.

The first data frame would be

1.0  2.0  3.0  4.0
2.0  3.0 -3.0 -3.0
1.0  4.0 -3.0  6.0
1.0  5.0  4.0  5.0

the second one would be

1.0  1.0  1.0  1.0
2.0  2.0  9.0  9.0
2.0  2.0  9.0  2.0
1.0  1.0  1.0  1.0

and the expected result

1.0  2.0  3.0  4.0
2.0  3.0  9.0  9.0
1.0  4.0  9.0  6.0
1.0  5.0  4.0  5.0

I suppose this can be done with a for loop but I haven't found the way to do it.

Thanks in advance

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
pacomet
  • 5,011
  • 12
  • 59
  • 111

1 Answers1

6

It's actually quite simple to do this without a for loop: if your data frames are A and B, then the command would be

A[A == -3] = B[A == -3]

In other words: for all the indices of A that have value -3, assign the values of B at the corresponding indices.

bnaul
  • 17,288
  • 4
  • 32
  • 30
  • Thanks for so a fast answer, it perfectly works. Sorry, seeing it was so simple I should have investigated more in basic R commands – pacomet Sep 05 '11 at 08:17