如何合并两列,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()或类似函数来生成表。
答案 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"))