Search code examples
rmergepaste

In R, how can I merge two data.frame columns using parentheses () as separation?


How can I merge two columns, 1) having the second one between parentheses or 2) having +- symbol as separation?

A <- data.frame(round(replicate(5, runif(10)),2))
A$collated <- paste(A$X1, A$X2, sep = " ")
A

This is the output I want to have:

     X1   X2   X3   X4   X5  collated
1  0.46 0.42 0.47 0.41 0.58 0.46 ± 0.42
2  0.59 0.61 0.26 0.78 0.09 0.59 ± 0.61
3  0.17 0.48 0.18 0.61 0.49 0.17 ± 0.48

Or this one:

     X1   X2   X3   X4   X5  collated
1  0.46 0.42 0.47 0.41 0.58 0.46 (0.42)
2  0.59 0.61 0.26 0.78 0.09 0.59 (0.61)
3  0.17 0.48 0.18 0.61 0.49 0.17 (0.48)

Eventually, I will be using kable() or similar function to produce a table.


Solution

  • We can use sprintf

    A$collated <- sprintf("%2.2f ± %2.2f", A$X1, A$X2)
    A
    #    X1   X2   X3   X4   X5    collated
    #1 0.46 0.42 0.47 0.41 0.58 0.46 ± 0.42
    #2 0.59 0.61 0.26 0.78 0.09 0.59 ± 0.61
    #3 0.17 0.48 0.18 0.61 0.49 0.17 ± 0.48
    

    Or

    A$collated <- sprintf("%2.2f (%2.2f)", A$X1, A$X2)
    A 
    #    X1   X2   X3   X4   X5    collated
    #1 0.46 0.42 0.47 0.41 0.58 0.46 (0.42)
    #2 0.59 0.61 0.26 0.78 0.09 0.59 (0.61)
    #3 0.17 0.48 0.18 0.61 0.49 0.17 (0.48)
    

    data

    A <- structure(list(X1 = c(0.46, 0.59, 0.17), X2 = c(0.42, 0.61, 0.48
     ), X3 = c(0.47, 0.26, 0.18), X4 = c(0.41, 0.78, 0.61), X5 = c(0.58, 
    0.09, 0.49)), .Names = c("X1", "X2", "X3", "X4", "X5"), 
    class = "data.frame", row.names = c("1", "2", "3"))