creating a dummy matrix from a concatenated column

2020-05-10 08:53发布

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条回答
老娘就宠你
2楼-- · 2020-05-10 09:17

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
查看更多
登录 后发表回答