2017-05-05 65 views
0

實施例的數據:列名稱到值

df <- data.frame(one = c(T, F, F, F, F, T), 
       two = c(F, F, F, F, T, F), 
       three = c(F, T, T, T, F, F)) 

真正的數據具有多個列,但是這會做,例如,我需要在以下數據框變爲df功能:

data.frame(type = c('one', 'three', 'three', 'three', 'two', 'one')) 

我看着堆和融化並像下面幾個奇怪的變通辦法:

df.new <- data.frame(type = c(rep.int(NA, 6))) 
for(i in 1:ncol(df)) { 
    df.new[,1] <- ifelse(df[,i], colnames(df)[i], df.new[,1]) 
} 
df.new 

但有沒有,做了功能這個?

+0

是的,你說得對。我在尋找時沒有發現這個問題 – Dutchmv

回答

1

在基礎R使用max.col試試這個矢量:

data.frame(type=names(df)[max.col(df)]) 

    # type 
# 1 one 
# 2 three 
# 3 three 
# 4 three 
# 5 two 
# 6 one