[R] if else
Cecilia Carmo
cecilia.carmo at ua.pt
Mon Jun 8 19:48:14 CEST 2009
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)
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,
Cecília (Universidade de Aveiro - Portugal)
More information about the R-help
mailing list