[R] if else
Chuck Cleland
ccleland at optonline.net
Mon Jun 8 20:01:40 CEST 2009
On 6/8/2009 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)
library(fortunes)
fortune("dog")
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)
mydata <- data.frame(firm, year, X1, X2)
mydata$X3 <- with(mydata, ifelse( is.na(X1) & !is.na(X2), X2,
ifelse(!is.na(X1) & is.na(X2), X1,
ifelse(!is.na(X1) & !is.na(X2), X1 + X2, NA))))
mydata
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,
>
> Cecília (Universidade de Aveiro - Portugal)
>
> ______________________________________________
> 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.
--
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894
More information about the R-help
mailing list