On Mon, Jun 8, 2009 at 1:48 PM, Cecilia Carmo <cecilia.ca...@ua.pt> wrote:

> I have the following dataframe:
> firm<-c(rep(1:3,4))
> year<-c(rep(2001:2003,4))
> X1<-rep(c(10,NA),6)
> X2<-rep(c(5,NA,2),4)
> data<-data.frame(firm, year,X1,X2)
> data
>
> So I want to obtain the same dataframe with a variable X3 that is:
> X1, if X2=NA
> X2, if X1=NA
> X1+X2 if X1 and X2 are not NA
>
> So my final data is
> X3<-c(15,NA,12,5,10,2,15,NA,12,5,10,2)
> finaldata<-data.frame(firm, year,X1,X2,X3)
>
> I've tried this
>
> finaldata<-ifelse(data$X1==NA,ifelse(data$X2==NA,NA,X2),ifelse(data$varvendas==NA,X1,X1+X2))
> But I got just NA in X3.
> Anyone could help me with this?
>

The problem here is that comparing NA to anything always gives NA, even for
NA==NA.  To check for NA, you need to use is.na, e.g.

data$X3 <- ifelse( is.na(data$X1), data$X2, ifelse( is.na(data$X2), data$X1,
data$X1+data$X2 )

(you don't need to handle the is.na(X1) & is.na(X2) case specially)

which you can make more compact using 'with':

data$X3 <- with(data, ifelse( is.na(X1), X2, ifelse( is.na(X2), X1, X1+X2
)))

Hope this helps,

           -s

        [[alternative HTML version deleted]]

______________________________________________
R-help@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.

Reply via email to