2017-09-20 3 views
1

Ich versuche, diese zu konvertieren -Konvertieren von String-Spalte zu Dummy-Variablen mit Nachschlüssel

> df.orig <- data.frame(id = c('foo', 'bar', 'foo'), action = c('abc','def','ghi')) 
> df.orig 
    id action 
1 foo abc 
2 bar def 
3 foo ghi 

In:

> df.new <- data.frame(id = c('foo', 'bar'), action_abc = c(1,0), action_def = c(0,1), action_ghi = c(1,0)) 
> df.new 
    id action_abc action_def action_ghi 
1 foo   1   0   1 
2 bar   0   1   0 

sparse.model.matrix und dcast mehrere Schlüssel nicht handhaben scheinen ('foo') sehr Gut.

> sparse.model.matrix(id ~ action - 1, df.orig) 
3 x 3 sparse Matrix of class "dgCMatrix" 
    actionabc actiondef actionghi 
1   1   .   . 
2   .   1   . 
3   .   .   1 
+0

'dcast' scheint gut zu funktionieren:' reshape2 :: dcast (df.orig, id ~ Aktion, fun.agg = Länge) ' – Frank

Antwort

2

Durch die Verwendung von table

df <- data.frame(id = c('foo', 'bar', 'foo'), action = c('abc','def','ghi'),stringsAsFactors = F) 

    table(df$id,df$action) 

     abc def ghi 
    bar 0 1 0 
    foo 1 0 1