【问题标题】:creating a dummy matrix from a concatenated column [duplicate]从连接列创建虚拟矩阵[重复]
【发布时间】:2018-11-18 06:28:06
【问题描述】:

我正在使用 R,我有一个如下所示的列:

relative
aunt
mother,grandmother

sister,mother

我想要的结果应该是这样的:

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

我该怎么做?提前致谢。

【问题讨论】:

标签: r dummy-variable


【解决方案1】:

你可以这样做:

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

或(对于整数):

+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

【讨论】:

  • 非常感谢。有效!现在唯一的问题是我在相对列中也有值“其他”:(阿姨,姐妹,母亲,祖母,其他)所以当母亲为真时,它也会看到“母亲”中的“其他”部分并将其放入“其他”
  • 它还在“grandmother”中找到“mother”
  • @MiladBotros 我编辑了我的答案。
  • 感谢它的工作!我真的很感激。
猜你喜欢
  • 1970-01-01
  • 2017-08-25
  • 2017-03-13
  • 2021-08-08
  • 2012-05-24
  • 2023-03-14
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
相关资源
最近更新 更多