how to split one row into multiple rows in R

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

for the sake of simplicity suppose I have a column in a data frame like the one below , each row contains multiple countries separated by ,

df <- data.frame(                   countries = c(                                 "UK , Spain , Germany , Italy , Netherlands" ,                                  "UK , Canada , AUS , China" ,                                  "Spain , AUS , Italy , Russia"                                 )                 ) 

This is how data looks like

                   countries 1 UK , Spain , Germany , Italy , Netherland 2                 UK , Canada , AUS , China 3              Spain , AUS , Italy , Russia 

how can we transform this to be something like

  countries 1   UK 2   Spain 3   Germany 4   Italy 5   Netherlands 6   UK 7   Canada 8   AUS 9   China 10  Spain 11  AUS 12  Italy 13  Russia 

回答1:

Just try:

data.frame(countries=unlist(strsplit(as.character(df$countries)," , "))) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!