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
  • 15,172
  • 7
  • 54
  • 83

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
  • 13,672
  • 21
  • 91
  • 162
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
  • 987
  • 7
  • 22
  • 1
    Sure. I'd also note that you're creating that dataframe in a bit of a strange way--I would do it in one line like so: `sample<-data.frame(x1=c(10,12,17,7,9,10), x2=c(NA,NA,NA,10,20,13), D=c(1,1,1,0,0,0))`. You might want to [brush up on data frames a bit](http://msenux.redwoods.edu/math/R/dataframe.php). – uptownnickbrown Mar 15 '13 at 18:25
  • 2
    (+1) you don't need a `which` there, do you? – Arun Mar 15 '13 at 18:45
  • 1
    No problem. Thanks for the note @Arun, I've added a note on removing the which() function for succinctness. – uptownnickbrown Mar 15 '13 at 20:18