2016-04-04 5 views
-1

Ich habe diesen Datenrahmen mydf genannt. Was ich tun muss, repliziert die Zeilen für jedes Element durch Komma getrennt in der Spalte cd und erhalten Sie das Ergebnis wie in result gezeigt.Wie repliziert Zeilen in Dataframe für jedes Komma getrennte Element in einer Spalte

mydf<-structure(list(cc = structure(1:3, .Label = c("a", "b", "c"), class = "factor"), 
    cd = structure(1:3, .Label = c("e,f,g", "f,g,s", "g,h,g"), class = "factor"), 
    individuals = structure(1:3, .Label = c("apple", "ball", 
    "cat"), class = "factor")), .Names = c("cc", "cd", "individuals" 
), row.names = c(NA, -3L), class = "data.frame") 

Ergebnis

cc cd   individuals 
a e   apple 
a f   apple 
a g   apple 
b f   ball 
b g   ball 
b s   ball 
c g   cat 
c h   cat 
c g   cat 

Antwort

1

dplyr Weg

library(stringi) 
library(dplyr) 
library(tidyr) 

mydf %>% 
    mutate(cd = cd %>% stri_split_fixed(",")) %>% 
    unnest(cd) 
+0

Bitte erläutern Sie, wie Sie Ihre Antwort das Problem löst, wird es jeder verstehen Ihre Lösung mit mehr Klarheit und für die Zukunft helfen. – Aziz

Verwandte Themen