2017-02-10 264 views
0

我試圖如下以產生一個新的變量:重新編碼ifelse或語句

如果種皮值是1和用於TESTB值爲1 ==>碼testAB爲1

如果種皮值1和缺少TESTB值或0 ==>碼testAB爲1

如果種皮值丟失或0和值TESTB是1 ==>碼testAB爲1

如果種皮值是0並且testB的值爲0 ==> code testAB as 0

如果testA的值缺失且testB的值缺失==> code testAB as NA

我想出的代碼如下所示不起作用。如果testA和testB是1,那麼似乎只產生一個1,否則就是NA。你有什麼建議?謝謝!

df2$testAB<-ifelse((df1$testA == 1) | (df1$testB == 1),1,0),1, 0,NA)) 
+0

也許'as.numeric(as.logical(DF1 $種皮)| as.logical(DF1 $ TESTB))' – Benjamin

回答

1

這應該得到你在找什麼

df1 <- data.frame(testA = c(1, 1, 1, 0, 0, 0, NA, NA, NA), 
        testB = c(0, 1, NA, 0, 1, NA, 0, 1, NA)) 

ind <- is.na(df1$testA) + is.na(df1$testB) < 2 
df1$testAB[!ind] <- NA 
df1$testAB[ind] <- as.numeric(as.logical(rowSums(df1[ind,], na.rm = TRUE))) 

> df1 
    testA testB testAB 
1  1  0  1 
2  1  1  1 
3  1 NA  1 
4  0  0  0 
5  0  1  1 
6  0 NA  0 
7 NA  0  0 
8 NA  1  1 
9 NA NA  NA 
+0

unforutnately這似乎並沒有工作,因爲它忽略了第一個0.基本上我想要一個或這樣做的命令:if testA == 1 | testB == 1 then testAB == 1. otherwise testAB == 0. if testA and testB == NA,then testAB == NA – victoria

+0

@Victoria回答更新以解釋值爲'0'和'NA'的情況 – manotheshark