Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine 3 columns to one in R

I want to combine mutiple columns to one column in a dataframe. I want a column that only shows lastname and first name.
I have a large data that looks similiar to the following:

Name_a<-c("","Steven", "Sara", "Eva", "(unknown)", "Joey", "", "Adam","(unknown)")
Last_n<-c("", "Lohan","","","Bright","Shane","Carter","","Graham")

person_n<-c("Shawn, Paris","(unknown", "Giselle, Sara","Dwayne, Eva","Brigth, Blue", "","Shane, Carter","Cardi, Adam","Graham, Mel" )

Alldata<-data.frame(Name_a,Last_n,person_n)

> Alldata
     Name_a Last_n      person_n
1                   Shawn, Paris
2    Steven  Lohan      (unknown
3      Sara        Giselle, Sara
4       Eva          Dwayne, Eva
5 (unknown) Bright  Brigth, Blue
6      Joey  Shane              
7           Carter Shane, Carter
8      Adam          Cardi, Adam
9 (unknown) Graham   Graham, Mel
>

This is what I have tried so fare:

Alldata<-mutate(Alldata,x=paste(Alldata$Name_a, Alldata$Last_n,Alldata$person_n))

Alldata

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     Name_a Last_n      person_n                             x
1                   Shawn, Paris                  Shawn, Paris
2    Steven  Lohan      (unknown         Steven Lohan (unknown
3      Sara        Giselle, Sara           Sara  Giselle, Sara
4       Eva          Dwayne, Eva              Eva  Dwayne, Eva
5 (unknown) Bright  Brigth, Blue (unknown) Bright Brigth, Blue
6      Joey  Shane                                 Joey Shane 
7           Carter Shane, Carter          Carter Shane, Carter
8      Adam          Cardi, Adam             Adam  Cardi, Adam
9 (unknown) Graham   Graham, Mel  (unknown) Graham Graham, Mel

the result is not what I’m looking for.

Any suggestion on how to fix this so that the new column will only show last name, first name?

>Solution :

Is this what you want?

library(dplyr)
library(stringr)
Alldata %>%
  mutate(x = case_when(
    ((str_detect(person_n, "unknown")) | (nchar(person_n) == 0)) ~ str_c(Last_n, Name_a, sep = ", "),
    TRUE ~ person_n
  ))

  x            
  <chr>        
1 Shawn, Paris 
2 Lohan, Steven
3 Giselle, Sara
4 Dwayne, Eva  
5 Brigth, Blue 
6 Shane, Joey  
7 Shane, Carter
8 Cardi, Adam  
9 Graham, Mel
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading