[R] if else

David Winsemius dwinsemius at comcast.net
Mon Jun 8 20:43:28 CEST 2009


On Jun 8, 2009, at 1:48 PM, Cecilia Carmo wrote:

> Hi R-helpers!
>
> 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)

data$X3 <- with(data, X1+X2)  # creates values for the valid pairs and  
NA otherwise
data[is.na(data$X3),"X3"] <- data$X1[is.na(data$X3)]  # NA's replaced  
with X1 including NA's
data[is.na(data$X3),"X3"] <- data$X2[is.na(data$X3)]  # remaining X1- 
NA's replaced with X2

 > data
    firm year X1 X2 X3
1     1 2001 10  5 15
2     2 2002 NA NA NA
3     3 2003 10  2 12
4     1 2001 NA  5  5
5     2 2002 10 NA 10
6     3 2003 NA  2  2
7     1 2001 10  5 15
8     2 2002 NA NA NA
9     3 2003 10  2 12
10    1 2001 NA  5  5
11    2 2002 10 NA 10
12    3 2003 NA  2  2

>
>
> 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?
>
> Thanks in advance,

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list