2016-06-21 32 views
0

考慮一個數據幀df1類似於所示的一個一個炎熱的編碼中的R數據幀

ID EDUCATION OCCUPATION  BINARY_VAR 
1 Undergrad Student    1 
2 Grad  Business Owner  1 
3 Undergrad Unemployed   0 
4 PhD   Other    1 

您可以創建以下

ID <- c(1:4) 
EDUCATION <- sample (c('Undergrad', 'Grad', 'PhD'), 4, rep = TRUE) 
OCCUPATION <- sample (c('Student', 'Business Owner', 'Unemployed', 'Other'), 4, rep = FALSE) 
BINARY_VAR <- sample(c(0, 1), 4, rep = TRUE) 
df1 <- data.frame(ID, EDUCATION, OCCUPATION, BINARY_VAR) 

# Convert to factor 
df1[, names(df1)] <- lapply(df1[, names(df1)] , factor) 

您自己的隨機df1使用R-代碼這需要推導出看起來像這樣的另一個數據幀df2

ID Undergrad Grad PhD Student Business Owner Unemployed Other BINARY_VAR 
1  1  0 0  1   0   0  0  1 
2  1  1 0  0   1   0  0  1 
3  1  0 0  0   0   1  0  0 
4  1  1 1  0   0   0  1  1 

你一定注意到的水平,EDUCATION下的其他因子水平也成立,因爲EDUCATIONID的最高教育水平。然而,這是次要目標。

我似乎無法找出方式獲得一個數據幀,每列給出與其父數據幀中的各個因子水平對應的真值。 R中是否有包裝?或者也許是一種方法來編碼?

我可以用melt這麼做嗎?

我通過previously asked question(s)看過看起來類似,但它們處理的發生頻率。


編輯:

所推薦的Sumedh,一個辦法做到這一點是使用dummyVarscaret

dummies <- dummyVars(ID ~ ., data = df1) 
df2 <- data.frame(predict(dummies, newdata = df1)) 
df2 <- df2 [1:7] 
+1

爲了您的主要目標,您可以使用'caret'中的'dummyVars' http://topepo.github.io/caret/preprocess.html – Sumedh

+1

對於PhD,您可以使用'df $ Grad [df $ PhD == 1] < - 1'和'df $ Undergrad [df $ PhD == 1] < - 1'。也許有更好的方法。 – Sumedh

+0

工作!有關如何獲得實際目標的任何想法? – aayush

回答

1

tidyrdplyrbase table()功能組合應該工作:

ID <- c(1:4) 
EDUCATION <- c('Undergrad', 'Grad', 'PhD', 'Undergrad') 
OCCUPATION <- c('Student', 'Business Owner', 'Unemployed', 'Other') 
BINARY_VAR <- sample(c(0, 1), 4, rep = TRUE) 
df1 <- data.frame(ID, EDUCATION, OCCUPATION, BINARY_VAR) 

# Convert to factor 
df1[, names(df1)] <- lapply(df1[, names(df1)] , factor) 

library(dplyr) 
library(tidyr) 

edu<-as.data.frame(table(df1[,1:2])) %>% spread(EDUCATION, Freq) 

for(i in 1:nrow(edu)) 
    if(edu[i,]$PhD == 1) 
    edu[i,]$Undergrad <-edu[i,]$Grad <-1 

truth_table<-merge(edu, 
     as.data.frame(table(df1[,c(1,3)])) %>% spread(OCCUPATION, Freq), 
     by = "ID") 

truth_table$BINARY_VAR<-df1$BINARY_VAR 
truth_table 

ID Grad PhD Undergrad Business Owner Other Student Unemployed BINARY_VAR 
1 0 0   1    0  0  1   0   1 
2 1 0   0    1  0  0   0   1 
3 1 1   1    0  0  0   1   0 
4 0 0   1    0  1  0   0   1 

編輯:增加了一個for循環更新由@ Sumedh早些時候建議的啓發PhD下的教育水平。

+0

@ Sumedh的解決方案的工作原理,除了 - 原始數據有12個因子水平,所以也許我必須創建一個函數在層面上以某種迭代的方式進行。此外,有大約160,000行... – aayush

+1

好吧,現在檢查它。 –