Wie konvertiert man einen Datenrahmen im langen Format in eine Liste mit einem geeigneten Format?


RätselAI

Ich habe einen Datenrahmen im folgenden langen Format:

1

Ich muss es in eine Liste umwandeln, die ungefähr so ​​​​aussehen sollte: 2

Wobei jedes der Hauptelemente der Liste die "Instanz-Nr." und seine Unterelemente sollten alle seine entsprechenden Parameter- und Wertepaare enthalten - im Format "Parameter X" = "abc", wie Sie im zweiten Bild sehen können, nacheinander aufgelistet.

Gibt es eine vorhandene Funktion, die dies kann? Ich konnte nicht wirklich welche finden. Jede Hilfe wäre wirklich dankbar.

Danke.

icj

Eine dplyr-Lösung

require(dplyr)
df_original <- data.frame("Instance No." = c(3,3,3,3,5,5,5,2,2,2,2),
                      "Parameter" = c("age", "workclass", "education", "occupation", 
                                      "age", "workclass", "education", 
                                      "age", "workclass", "education", "income"),
                      "Value" = c("Senior", "Private", "HS-grad", "Sales",
                                  "Middle-aged", "Gov", "Hs-grad",
                                  "Middle-aged", "Private", "Masters", "Large"),
                      check.names = FALSE)
    
# the split function requires a factor to use as the grouping variable.
# Param_Value will be the properly formated vector
df_modified <- mutate(df_original,
                      Param_Value = paste0(Parameter, "=", Value))
# drop the parameter and value columns now that the data is contained in Param_Value
df_modified <- select(df_modified,
                      `Instance No.`,
                      Param_Value)

# there is now a list containing dataframes with rows grouped by Instance No.
list_format <- split(df_modified, 
                     df_modified$`Instance No.`)

# The Instance No. is still in each dataframe. Loop through each and strip the column.
list_simplified <- lapply(list_format, 
                          select, -`Instance No.`)

# unlist the remaining Param_Value column and drop the names.                      
list_out <- lapply(list_simplified , 
                   unlist, use.names = F)
                     

Es sollte nun eine Liste von Vektoren vorhanden sein, die wie gewünscht formatiert ist.

$`2`
[1] "age=Middle-aged"   "workclass=Private" "education=Masters" "income=Large"     

$`3`
[1] "age=Senior"        "workclass=Private" "education=HS-grad" "occupation=Sales" 

$`5`
[1] "age=Middle-aged"   "workclass=Gov"     "education=Hs-grad"

Die gepostete data.table-Lösung ist schneller, aber ich denke, das ist etwas verständlicher.

Verwandte Artikel