Create a column whose outcome is the random match of two other columns in R

Viewed 71

I have a very long data.frame that looks like this

col1 <- c("a","b","c","d")
col2 <- c("E","F","G","H")
df <- data.frame(col1,col2)
  col1 col2
1    a    E
2    b    F
3    c    G
4    d    H

I want to create column, "col3", whose outcome is product of the random combination of the elements in col1 and col2.

for example I want something like this

  col1 col2 col3
1    a    E a-G
2    b    F b-H
3    c    G c-E
4    d    H d-F

any help por guidance is highly appreciated.

2 Answers

With data.table:

library(data.table)
setDT(df)
df[,col3:=paste(col1,'-',sample(col2))][]

   col1 col2  col3
1:    a    E a - F
2:    b    F b - E
3:    c    G c - H
4:    d    H d - G

or base R:

df$col3 <- paste(df$col1,'-',sample(df$col2))

One dplyr option could be:

df %>%
 mutate(col3 = paste(sample(col1), sample(col2), sep = "-"))

  col1 col2 col3
1    a    E  c-E
2    b    F  b-H
3    c    G  a-F
4    d    H  d-G
Related