[R] conditional data replace (recode, change or whatsoever)

R. Michael Weylandt <michael.weylandt@gmail.com> michael.weylandt at gmail.com
Wed Aug 3 13:10:44 CEST 2011


As others have noted, this is discussed in many free R tutorials, but if you want to do it in one line I think this should do it:

X[is.NA(X[,"b"])&(X[,"c"]==0),"b"]<-"2011-07-28" #where X is the name of the data frame. 

It's a somewhat convoluted line of code but if you read it inside out the logic is clear:

Find those rows where column b is NA and c is 1 by searching all rows of the relevant column (the X[,something] syntax): select those rows and the b column. Put the desired date in those slots. let me know of I can further clarify this. I changed the date assuming a typo on your end. 

Welcome and good luck getting started with R,

Michael Weylandt


On Aug 3, 2011, at 4:05 AM, zcatav <zcatav at gmail.com> wrote:

> Hello,
> I have a big data.frame, a piece of it as follows.
> 
>   a            b                c        d
> 1    58009    2010-11-02    0        NA
> 2    114761    NA                1        2008-11-05
> 3    184440    NA                1        2009-12-08
> 4    189372    NA                0        NA
> 5    105286    NA                0        NA
> 6    186717    NA                0        NA
> 7    189106    NA                0        NA
> 8    127306    NA                0        NA
> 9    157342    2011-04-25    0        NA
> 
> I want to replace b[NA] values with "20011-07-28" where c==0. I use rstudio
> and i'm a novice.
> 
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/conditional-data-replace-recode-change-or-whatsoever-tp3714715p3714715.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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