2016-07-19 22 views
0

Die Datenrahmen Informationen in diesem Format enthält:Erhalten Sie Spalten aus der Spalte Werte

Type  Value 
------------------- 
catA  one 
catB  two 
catA  three 

Mein Ziel ist es, die Datenrahmen zu diesem Format (Typ Werte als Spalten) zu konvertieren:

catA  catB 
----------------- 
one   - 
    -   two 
three   - 

ich gewesen sein in "Dummy-Variablen" schauen, aber es ist nicht das, was ich brauche. Kann mir jemand eine Idee geben?

Antwort

3
library(reshape2) 
df <- data.frame(Type=c("catA","catB","catA"),value=c("one","two","three")) 
df 
# Type value 
# 1 catA one 
# 2 catB two 
# 3 catA three 

dcast(df,value~Type) 
# value catA catB 
# 1 one one <NA> 
# 2 three three <NA> 
# 3 two <NA> two 

dcast(df,Type~value) 
# Type one three two 
# 1 catA one three <NA> 
# 2 catB <NA> <NA> two 

Zur Erhaltung der Reihenfolge der value

df$Type <- factor(df$Type,c("catA","catB")) 
df$value <- factor(df$value,c("one","two","three")) 

dcast(df,Type~value) 
# Type one two three 
# 1 catA one <NA> three 
# 2 catB <NA> two <NA> 

dcast(df,value~Type) 
# value catA catB 
# 1 one one <NA> 
# 2 two <NA> two 
# 3 three three <NA> 
: Dies kann mit unstack erreicht werden
1

Sie haben eine lange Format-Tabelle und Sie möchten ein breites Format haben. Verwenden Sie dcast() Funktion von reshape2 Paket dafür.

0

Da Sie nicht mit einem rechteckigen Datensatz arbeiten, kann es sinnvoller sein, das Ergebnis in einer Liste zu speichern.

unstack(df, form=Value~Type) 
$catA 
[1] "one" "three" 

$catB 
[1] "two" 

Daten

df <- read.table(header=T, text="Type  Value 
catA  one 
catB  two 
catA  three") 
Verwandte Themen