replace the values using iflelse in R

自作多情 提交于 2019-12-07 11:05:31

问题


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?


回答1:


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]))



回答2:


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])]


来源:https://stackoverflow.com/questions/15439359/replace-the-values-using-iflelse-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!