我试图粘贴不同的值,如下所示。但是没有得到想要的输出
paste0(c("A","B"),c("A1", "B1"))
[1] "AA1" "BB1"
预期输出
[1] "AA1" "AB1" "BA1" "BB1"
我们可以使用expand.grid
和sprintf
:
x <- expand.grid( c("A","B"), c("A1", "B1"))
sprintf('%s%s', x[,1], x[,2])
[1] "AA1" "BA1" "AB1" "BB1"
由于两个矢量的length
相同,因此paste
将进行逐元素粘贴。为了避免这种情况,rep
选择其中一个向量,recycle
选择另一个
paste0(rep(c("A","B"), each = 2), c("A1", "B1"))
[1] "AA1" "AB1" "BA1" "BB1"
或者outer
和paste
同时使用
c(outer(c("A", "B"), c("A1", "B1"), FUN = paste, sep = ""))
[1] "AA1" "BA1" "AB1" "BB1"