在R中使用if语句创建一个新变量

时间:2014-12-22 17:07:52

标签: r if-statement

我有以下情况 在我的数据集中,有两个变量(x1和x2)。

mydata <- data.frame(x1=c("a","b","c","n","a","d","b","l","a","c","t","a","b","d","c","l","n","b"), x2=c(1,NA,5,2,NA,5,4,NA,2,NA,2,6,NA,6,NA,2,6,NA))
mydata[is.na(mydata)] <- " "

    x1  x2
1   a   1
2   b    
3   c   5
4   n   2
5   a    
6   d   5
7   b   4
8   l    
9   a   2
10  c    
11  t   2
12  a   6
13  b    
14  d   6
15  c    
16  l   2
17  n   6
18  b   

我想创建第三个变量,我们称之为x3,定义为

如果(x1 = a或b或c AND x2 =“”),则x3 = 1,否则x3 = 0

输出

    x1  x2  x3
1   a   1   0
2   b       1
3   c   5   0
4   n   2   0
5   a       1
6   d   5   0
7   b   4   0
8   l       0
9   a   2   0
10  c       1
11  t   2   0
12  a   6   0
13  b       1
14  d   6   0
15  c       1
16  l   2   0
17  n   6   0
18  b       1

1 个答案:

答案 0 :(得分:1)

你可以尝试

mydata$x3 <- (mydata$x1 %in% c('a', 'b', 'c') & mydata$x2==' ')+0
mydata$x3
#[1] 0 1 0 0 1 0 0 0 0 1 0 0 1 0 1 0 0 1

或者@David Arenburg评论,创建列的其他选项包括transformwithin等函数

transform(mydata, x3 = (x1 %in% letters[1:3] & x2 == ' ') + 0L)