说我有:
df = data.frame(var = rnorm(10),
apple = c(rep(1, 5), rep(0, 5)),
pear = c(rep(0, 5), rep(1, 3), rep(0, 2)),
banana = c(rep(0, 8), c(rep(1, 2))))
df
# var apple pear banana
# 1 0.83909475 1 0 0
# 2 -0.49670792 1 0 0
# 3 -0.33740589 1 0 0
# 4 -0.94037675 1 0 0
# 5 0.50043212 1 0 0
# 6 -0.05489703 0 1 0
# 7 0.90638714 0 1 0
# 8 -0.01192395 0 1 0
# 9 1.80543603 0 0 1
# 10 0.56456775 0 0 1
我想要
# var Group
# 1 0.83909475 apple
# 2 -0.49670792 apple
# 3 -0.33740589 apple
# 4 -0.94037675 apple
# 5 0.50043212 apple
# 6 -0.05489703 pear
# 7 0.90638714 pear
# 8 -0.01192395 pear
# 9 1.80543603 banana
# 10 0.56456775 banana
使用melt
或类似的东西是否有一种优雅的方法?
答案 0 :(得分:2)
您可以使用矩阵乘法
来完成此操作autoindex
或选择最大的列(因为列是互斥的)
colnames(df[2:4])[as.matrix(df[2:4]) %*% 1:3]
或使用colnames(df[2:4])[max.col(df[2:4])]
reshape2::melt