Vin
Vin

Reputation: 151

how do I extract a part of data from a column and and paste it n another column using R?

I want to extract a part of data from a column and and paste it in another column using R:

My data looks like this:

names <- c("Sia","Ryan","J","Ricky")
country <- c("London +1234567890","Paris", "Sydney +0123458796", "Delhi")
mobile <- c(NULL,+3579514862,NULL,+5554848123)
data <- data.frame(names,country,mobile)
data
> data
  names            country     mobile
1   Sia London +1234567890 NULL
2  Ryan              Paris +3579514862
3     J Sydney +0123458796 NULL
4 Ricky              Delhi +5554848123

I would like to separate phone number from country column wherever applicable and put it into mobile.

The output should be,

> data
  names            country     mobile
1   Sia             London +1234567890    
2  Ryan              Paris +3579514862
3     J             Sydney +0123458796
4 Ricky              Delhi +5554848123

Upvotes: 1

Views: 132

Answers (1)

Cettt
Cettt

Reputation: 11981

You can use the tidyverse package which has a separate function.

Note that I rather use NA instead of NULL inside the mobile vector. Also, I use the option, stringsAsFactors = F when creating the dataframe to avoid working with factors.

names <- c("Sia","Ryan","J","Ricky")
country <- c("London +1234567890","Paris", "Sydney +0123458796", "Delhi")
mobile <- c(NA, "+3579514862", NA, "+5554848123")
data <- data.frame(names,country,mobile, stringsAsFactors = F)

library(tidyverse)

data %>% as_tibble() %>% 
  separate(country, c("country", "number"), sep = " ", fill = "right") %>% 
  mutate(mobile = coalesce(mobile, number)) %>% 
  select(-number)

# A tibble: 4 x 3
  names country mobile     
  <chr> <chr>   <chr>      
1 Sia   London  +1234567890
2 Ryan  Paris   +3579514862
3 J     Sydney  +0123458796
4 Ricky Delhi   +5554848123

EDIT If you want to do this without the pipes (which I would not recommend because the code becomes much harder to read) you can do this:

select(mutate(separate(as_tibble(data), country, c("country", "number"), sep = " ", fill = "right"), mobile = coalesce(mobile, number)), -number)

Upvotes: 2

Related Questions