SiH
SiH

Reputation: 1546

Separate a column into multiple column in the desired way mentioned

I can separate (using ", ") a column into multiple column.

The idea is to reverse the order of words (separated by ", ") and then separate them into multiple columns. Example of reversing - "CA, SF" becomes "SF, CA"

Below is an example

library(tidyverse)

# sample example 
tbl <- tibble(
  letter = c("US, CA, SF","NYC", "Florida, Miami")
)

# desired result
tbl_desired <- tibble(
  country = c("US", NA, NA),
  state = c("CA", NA, "Florida"),
  city = c("SF", "NYC", "Miami")
)


# please edit it to get the desired result
tbl %>%
  # please add line to reverse the string
  mutate() %>% 
  separate(letter, into = c("country", "state", "city"), sep = ", ")



Upvotes: 2

Views: 72

Answers (1)

akrun
akrun

Reputation: 887741

There is fill argument in separate which can be used (by default, it is "warn"), but we can change that to either "right" or "left". Here, it should be filled from the "left"

library(tidyr)
separate(tbl, letter, into = c("country", "state", "city"), 
     sep = ", ", fill = "left")

-output

# A tibble: 3 × 3
  country state   city 
  <chr>   <chr>   <chr>
1 US      CA      SF   
2 <NA>    <NA>    NYC  
3 <NA>    Florida Miami

Upvotes: 2

Related Questions