2016-03-05 71 views
1

說我有:熔體假人分爲一組變量

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或類似的東西要做到這一點?

回答

2

你可以用矩陣乘法做到這一點

colnames(df[2:4])[as.matrix(df[2:4]) %*% 1:3] 

,或者通過選擇最大的列(如列是互相排斥的)

colnames(df[2:4])[max.col(df[2:4])] 

或使用reshape2::melt

m <- melt(df, id.vars='var') 
m[m$value != 0, -3]