creating a dummy matrix from a concatenated column [duplicate]

Deadly 提交于 2019-12-04 07:12:56

问题


I'm using R and I have a column that looks like this:

relative
aunt
mother,grandmother

sister,mother

My desired outcome should look like this:

mother  sister aunt grandmother
0       0      1    0
1       0      0    1
0       0      0    0
1       1      0    0

How can I do that? Thanks in advance.


回答1:


You can do:

relative <- c("aunt", "mother,grandmother", "sister,mother", "", "other")
R <- strsplit(relative, ',')
r <- unique(unlist(R))
result <- t(sapply(R, function(Ri) if (length(Ri)==0) rep(FALSE, length(r)) else r %in% Ri))
colnames(result) <- r
result
# > result
#       aunt mother grandmother sister other
# [1,]  TRUE  FALSE       FALSE  FALSE FALSE
# [2,] FALSE   TRUE        TRUE  FALSE FALSE
# [3,] FALSE   TRUE       FALSE   TRUE FALSE
# [4,] FALSE  FALSE       FALSE  FALSE FALSE
# [5,] FALSE  FALSE       FALSE  FALSE  TRUE

or (for integers):

+result
# > +result
#      aunt mother grandmother sister other
# [1,]    1      0           0      0     0
# [2,]    0      1           1      0     0
# [3,]    0      1           0      1     0
# [4,]    0      0           0      0     0
# [5,]    0      0           0      0     1


来源:https://stackoverflow.com/questions/50756486/creating-a-dummy-matrix-from-a-concatenated-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!