Home > Net >  How to merge characters of two columns?
How to merge characters of two columns?

Time:03-07

I have a df1:

ID   Date
23  4/5/2011
12  4/7/2012
14  6/17/2020
90  12/20/1994

Currently these columns are both character classes. I would like to create a third column that merges these two columns with an underscore. The output would look like:

ID   Date       Identifier
23  4/5/2011    23_4/5/2011
12  4/7/2012    12_4/7/2012
14  6/17/2020   14_6/17/2020
90  12/20/1994  90_12/20/1994

CodePudding user response:

Use paste():

df1 <- data.frame(ID = c("23","13","14","90"), Date = c("4/5/2011", "4/7/2012", "6/17/2020", "12/20/1994"))
df1 |> 
  dplyr::mutate(Identifier = paste(ID, Date, sep = "_"))
#>   ID       Date    Identifier
#> 1 23   4/5/2011   23_4/5/2011
#> 2 13   4/7/2012   13_4/7/2012
#> 3 14  6/17/2020  14_6/17/2020
#> 4 90 12/20/1994 90_12/20/1994

Created on 2022-03-06 by the reprex package (v2.0.1)

CodePudding user response:

Using base R, you could do:

Reprex

  • your data
df <- read.table(text = "ID   Date
23  4/5/2011
12  4/7/2012
14  6/17/2020
90  12/20/1994", header = TRUE)
  • Code
df$Identifier <- paste0(df$ID, "_", df$Date)
  • Output
df
#>   ID       Date    Identifier
#> 1 23   4/5/2011   23_4/5/2011
#> 2 12   4/7/2012   12_4/7/2012
#> 3 14  6/17/2020  14_6/17/2020
#> 4 90 12/20/1994 90_12/20/1994

Created on 2022-03-06 by the reprex package (v2.0.1)

  • Related