[R] Replace NA's with value in the next row

Jim Lemon jim at bitwrit.com.au
Thu Nov 14 09:02:06 CET 2013


On 11/14/2013 04:02 PM, dila radi wrote:
> Hi all,
>
> I have a data set which treat missing value as NA and now I need to replace
> all these NA's by using number in the same row but different column.
>
> Here is the part of my data:
>   V1 V2 V3 V4 V5 V6 V7  0 0 0 1.2 0 0 0.259  0 0 12.8 0 23.7 0 8.495  6 0
> 81.7 0.2 0 20 19.937  0 1.5 60.9 0 0 15.5 13.900  1 13 56.8 17.5 32.8 6.4
> 27.654  4 3 66.4 2 0.3 NA 17.145
>
>
> I want to replace (V6, 6) with (V7, 6). I have about 1000 NA's in V6 which
> I want to replace  with the same row in V7. The other values in V6, I want
> to keep remain the same.
>
> How to achieve this? Assuming my data is called "Targetstation",  I have
> tried this:
>
> Targetstation<- within(Targetstation, v6<- replace(v6, is.na(v6), v7[is.na
> (v6)]))
>
> But R gives me this:
>
> Warning messages:
>
> 1: In is.na(v6) : is.na() applied to non-(list or vector) of type 'NULL'
>
> 2: In is.na(v6) : is.na() applied to non-(list or vector) of type 'NULL'
>
>
Hi Dila,
You could do this like this:

V6NA<-is.na(Targetstation$V6)
Targetstation$V6[V6NA]<-Targetstation$V7[V6NA]

but if you want to use the above, I think you will have to replace the 
is.na(V6) with is.na(Targetstation$V6) or use the method above.

Jim



More information about the R-help mailing list