我已數據集ifelse功能組中的R
ID <- c(1,1,2,2,2,2,3,3,3,3,3,4,4,4)
Eval <- c("A","A","B","B","A","A","A","A","B","B","A","A","A","B")
med <- c("c","d","k","k","h","h","c","d","h","h","h","c","h","k")
df <- data.frame(ID,Eval,med)
> df
ID Eval med
1 1 A c
2 1 A d
3 2 B k
4 2 B k
5 2 A h
6 2 A h
7 3 A c
8 3 A d
9 3 B h
10 3 B h
11 3 A h
12 4 A c
13 4 A h
14 4 B k
我嘗試x
和y
,由組ID和eval來創建變量。對於每個ID,if Eval = A, and med = "h" or "k"
,我設置x = 1
,其他明智x = 0
,if Eval = B and med = "h" or "k"
,我設置y = 1
,其他明智y = 0
。我用我不喜歡的方式,我得到了答案,但它看起來不是很大
df <- data.table(df)
setDT(df)[, count := uniqueN(med) , by = .(ID,Eval)]
setDT(df)[Eval == "A", x:= ifelse(count == 1 & med %in% c("k","h"),1,0), by=ID]
setDT(df)[Eval == "B", y:= ifelse(count == 1 & med %in% c("k","h"),1,0), by=ID]
ID Eval med count x y
1: 1 A c 2 0 NA
2: 1 A d 2 0 NA
3: 2 B k 1 NA 1
4: 2 B k 1 NA 1
5: 2 A h 1 1 NA
6: 2 A h 1 1 NA
7: 3 A c 3 0 NA
8: 3 A d 3 0 NA
9: 3 B h 1 NA 1
10: 3 B h 1 NA 1
11: 3 A h 3 0 NA
12: 4 A c 2 0 NA
13: 4 A h 2 0 NA
14: 4 B k 1 NA 1
那麼我要崩潰的行獲得唯一的ID,我不知道如何收行,任何想法?
輸出
ID x y
1 0 0
2 1 1
3 0 1
4 0 1
不應該的「Y」爲ID 1是0,因爲只有來港在 – akrun
是啊,你說得對 – BIN
對於因爲Eval是'A',med是'h',所以你的數據的第11行不應該是'1'嗎? – Maiasaura