Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace the values using iflelse in R

I have a very trivial question with the data as below :

sample<-list(c(10,12,17,7,9,10),c(NA,NA,NA,10,12,13),c(1,1,1,0,0,0))
sample<-as.data.frame(sample)
colnames(sample)<-c("x1","x2","D")

>sample
x1  x2  D
10  NA  1
12  NA  1
17  NA  1
7   10  0
9   20  0
10  13  0

Note: the number of observations with D=1 is same as D=0

Now, I want to create a variable x3 that has values related to D=0 when D=1 and values related to D=1 when D=0. The expected output:

x1  x2  D   x3
10  NA  1   10
12  NA  1   20
17  NA  1   13
7   10  0   NA
9   20  0   NA
10  13  0   NA

I tried using ifelse function as follows:

sample.data$x3<-with(sample.data, ifelse(D==1,x2[which(D==0)],x2[which(D==1)]))

I got the following error:

logical(0)

I also tried the following:

sample.data$x3<-with(sample.data, ifelse(D==1,tail(x2,3),head(x2,3)))

Again, I got the same error:

logical(0)

Any idea what is going here?

like image 713
Metrics Avatar asked Jan 14 '23 22:01

Metrics


1 Answers

do you know data.table, here is a solution with it...

install.packages("data.table")
library(data.table)

sample = as.data.table(sample)
sample[,x4:=ifelse(D==1,x2[D==0],x2[D==1])]
like image 80
statquant Avatar answered Jan 19 '23 12:01

statquant