在R中,如何使用括号()作为分隔合并两个data.frame列?

时间:2017-04-07 15:14:18

标签: r merge paste

如何合并两列,1)括号中的第二列或2)+ - 符号作为分隔?

A <- data.frame(round(replicate(5, runif(10)),2))
A$collated <- paste(A$X1, A$X2, sep = " ")
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

或者这个:

     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)

最终,我将使用kable()或类似函数来生成表。

1 个答案:

答案 0 :(得分:1)

我们可以使用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

或者

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)

数据

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"))