How to split one line into several lines in R

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

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

Here's what the 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 as 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
+7
source share
2 answers

Just try:

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

You can use 'Separate Hands' from the tidyr package:

df = separate_rows(df,1,sep = ",")
0
source

All Articles