Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201977

Split big column of rbinded columns to make wide data in R

$
0
0

I have a data frame which has a column of city names. Country names are specified for the cities. However, this is done in a way where one cell has a country name in it and then the following cells have city names from that country. It looks like this:

countries = tibble(
  city = c('Belgium', 'Bruxelles', 'Antwerpen', 'Bulgaria', 'Sofia', 'Plovdiv')
)

# A tibble: 6 x 1
#  city     
#   <chr>    
# 1 Belgium  
# 2 Bruxelles
# 3 Antwerpen
# 4 Bulgaria 
# 5 Sofia    
# 6 Plovdiv 

I want to have a column that identifies the country for each city, like this:

#  city     country
#   <chr>    <chr>
# 1 Bruxelles  Belgium
# 2 Antwerpen  Belgium
# 3 Sofia  Bulgaria    
# 4 Plovdiv  Bulgaria

I figured out how to mark whether a cell in the city column in the first example is actually a city or a country, but then I got stuck.


Viewing all articles
Browse latest Browse all 201977

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>