在R中使用iflelse替换值 [英] replace the values using iflelse in R

查看:114
本文介绍了在R中使用iflelse替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下数据有一个非常微不足道的问题:

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

注意:D = 1的观察数与D = 0相同

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

现在,我想在 D时创建一个变量 x3 ,其值与 D = 0 相关当 D = 0 时,= 1 和与 D = 1 相关的值。预期产出:

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

我尝试使用 ifelse 函数,如下所示:

I tried using ifelse function as follows:

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

我收到以下错误:

logical(0)

我还尝试了以下内容:

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?

推荐答案

您的命令中的逻辑是合理的,但您正在错误地引用数据帧。您只需要在代码行中的示例之后删除 .data 。所以这个命令会给你你需要的东西:

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



< hr>

然而,该代码仍然有点冗长。


That code is still a little verbose however.

正如@Arun在评论中指出的那样,你没有在选择 x2 值时,需要包含which()函数作为 ifelse 的结果。以下代码将给出相同的结果:

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

这篇关于在R中使用iflelse替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆