这是我的原始向量(长度可能会有所不同)
c("e1","e2","e3","e4","e5","e6","e7","e8","e9","e10")
我想复制每个元素(保持顺序)并将属性“ a”赋给第一个匹配项,将“ b”赋给第二个出现,以得到:
c("e1a","e1b","e2a","e2b","e3a","e3b","e4a","e4b","e5a","e5b","e6a","e6b","e7","e7b","e8a","e8b","e9a","e9b","e10a","e10b")
如何在R中以一种简洁的方式做到这一点?
答案 0 :(得分:2)
您可以使用rep(each = 2)
来获取重复项,然后使用paste0
来添加后缀字母,如下所示。
这是向量回收的一个很好的例子; paste0
将使用c("a", "b")
的元素,直到较长向量的长度自动耗尽为止。因此,您可以使用原始vec
的任何长度来执行此操作。许多base和package R函数将执行类似的操作。
vec <- c("e1","e2","e3","e4","e5","e6","e7","e8","e9","e10")
paste0(rep(vec, each = 2), c("a", "b"))
#> [1] "e1a" "e1b" "e2a" "e2b" "e3a" "e3b" "e4a" "e4b" "e5a" "e5b"
#> [11] "e6a" "e6b" "e7a" "e7b" "e8a" "e8b" "e9a" "e9b" "e10a" "e10b"
由reprex package(v0.2.0)于2018-08-07创建。