4

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?

Metrics
  • 14,596
  • 7
  • 50
  • 80

2 Answers2

5

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])]
statquant
  • 12,918
  • 18
  • 86
  • 153
4

The logic in your command is sound, but you are referencing the dataframe incorrectly. You just need to remove .data after sample throughout your line of code. So this command will give you what you need:

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

That code is still a little verbose however.

As @Arun has noted in the comments, you don't need to include the which() function when selecting x2 values to use as a result of your ifelse. The following code will give you identical results:

sample$x3<-with(sample,ifelse(D==1,x2[D==0],x2[D==1]))
uptownnickbrown
  • 957
  • 7
  • 22