简体   繁体   中英

Is there a way to join a couple of columns using a R function?

I have columns Name in list.x and Name , Suburb in list.y. I am willing to join them list.x and list.y. The problem is, Name in list.x is,

  1. Name in list.x separated by ! whereas in list.y separated by ,
  2. Name in list.x First name then last na,e ! whereas in list.y Last name then First name.
list.x = data.frame(
         Name = c("John!Citizen","Dipayan!Banerjee","Smith!Langley!White"))

list.y = data.frame(
Name = c("White,Smith,Langley","Citizen,John","Banerjee,Dipayan"),
Suburb = c("Langley","Mars","Here"))

I want to match x.list with y.list by Product and Molecule

orderAlp<-function(x){
  str_split(x, ' ') %>% lapply(x, 'sort') %>%  lapply(x, 'paste', collapse=' ') %>% unlist(x)
}
x.list %>% full_join(y.list,by="Product") %>% 
  mutate(Moleculs.x=str_replace_all(Moleculs.x,"!",","),
         Molecules.y=orderAlp(Molecules.y))

I wish to add output here but the obs name so long and I couldn't add it.

Try this:

library(dplyr)
library(tidyr)

x.list %>%
  separate_rows(Moleculs.x, sep = '!') %>%
  rename(Molecules =  Moleculs.x) %>%
  inner_join(y.list %>%
               separate_rows(Molecules.y, sep = ',') %>%
               rename(Molecules = Molecules.y), by = c("Product", "Molecules")) -> result

result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM