[R] Conditional replacement of NA depending on value in the previous column
Phil Spector
spector at stat.berkeley.edu
Tue Mar 23 19:51:45 CET 2010
Mark -
Does this do what you want?
dat = data.frame(X1=c(1,1),X2=c(1,1),X3=c(1,1),
X4=c(0,1),X5=c(NA,NA),x6=c(NA,1))
fixit = function(x){
y = c(x[-1],0)
x[is.na(y) & is.na(x)] = 0
x}
t(apply(dat,1,fixit))
X1 X2 X3 X4 X5 x6
[1,] 1 1 1 0 0 0
[2,] 1 1 1 1 NA 1
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Tue, 23 Mar 2010, Mark Na wrote:
> Dear R-helpers,
>
> I have a dataframe like this:
>
> ID X1 X2 X3 X4 X5 X6
> 49 1 1 1 0 NA NA
> 50 1 1 1 1 NA 1
>
> I would like to convert a missing value (NA) that follows a 0 (zero) or
> another missing value (NA) into a 0 (zero).
>
> So, the above lines would be converted to:
>
> ID X1 X2 X3 X4 X5 X6
> 49 1 1 1 0 0 0
> 50 1 1 1 1 NA 1
>
> I have been struggling with this all morning, so any help you could provide
> would be much appreciated.
>
> Thank you!
>
> Mark Na
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list