我有這樣的數據幀使用其他列
dat = data.frame(Type = c("A","A","B","B","C","C","D"), NextType = c("A", "B","B", "C","C","D",NA),
A = c(rep(0,7)),
B = rep(0,7),
C = rep(0,7) ,
D = rep(0,7),
stringsAsFactors = F)
dat
Type NextType A B C D
1 A A 0 0 0 0
2 A B 0 0 0 0
3 B B 0 0 0 0
4 B C 0 0 0 0
5 C C 0 0 0 0
6 C D 0 0 0 0
7 D <NA> 0 0 0 0
什麼來填充列A,B和C和d爲1,如果該列名(A,B,C的最佳方式應用公式某些列,d等)=類型= NextType
所以
column A would be 1,0,0,0,0,0,0
column B would be 0,0,1,0,0,0,0
column C would be 0,0,0,0,1,0,0
column D would be 0,0,0,0,0,0,0
注意 - 這是動態的。我有4列以上A,B和C和D,但可以有10,20或任何數量的列。
對不起,我根本沒有匹配的情況下排除了案件。你能看到編輯? – user3022875
所以你想要一個專門爲零的列? – Psidom
在這種情況下,你可以嘗試使用'model.matrix',創建一個與'Type'列+其他級別相同級別的因子類型的關鍵列,'model.matrix'將保留缺少的額外級別。 (type,NextType)%>%mutate(key = factor(if_else(Type == NextType&!is.na(Type)&!is.na(NextType),Type,「other」), levels = c(「other」,unique(Type))))%>%bind_cols(。,as.data.frame(model.matrix(〜key - 1,。)))%>%select(-keyother, - 鍵)' – Psidom