[英]Create a new variable from conditions on multiple variables in R using ifelse condition
[英]Create a list using dummy variables in R
我有三個虛擬變量,它們指示數據源
DS1 DS2 DS3
Pers1 1 0 0
Pers2 0 1 0
Pers3 0 1 1
我想擁有
Source
Pers1 "DS1"
Pers2 "DS2"
Pers3 "DS2"|"DS3"
任何幫助,將不勝感激
我會做這樣的事情:
df = data.frame(DS1 = c(1,0,0),
DS2 = c(0,1,1),
DS3 = c(0,0,1))
df$source = apply(df == 1, 1, function(x) paste(names(df)[x], collapse = "|"))
> df
DS1 DS2 DS3 source
1 1 0 0 DS1
2 0 1 0 DS2
3 0 1 1 DS2|DS3
where apply
在df == 1
data.frame的行上循環,並paste
創建一個字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.