R语言 复制并将修改后的字符串插入到向量中而不进行排序[重复]

ehxuflar  于 2023-05-11  发布在  其他
关注(0)|答案(4)|浏览(102)

此问题已在此处有答案

How to merge 2 vectors alternating indexes?(6个回答)
2天前关闭。
假设我有一个字符串向量:

vec <- c("D", "A", "B", "A")

我想插入一个修改后的字符串(在字符串的末尾连接“_2”),直接在原始字符串之后,不排序。
预期输出:

[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

我正在寻找比我下面分享的更简单的解决方案,我认为这可能是不必要的过于复杂。

x759pob2

x759pob21#

尝试c + rbind沿着paste0

> c(rbind(vec, paste0(vec, "_2")))
[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

或带有outer的更长版本

> c(t(outer(vec, c("", "_2"), paste0)))
[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

如果你不介意效率,你可以试试

> scan(text = gsub("(.*)", "\\1 \\1_2", vec), what = "", quiet = TRUE)
[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

因为当具有较长向量时scan可能较慢。

djp7away

djp7away2#

也可以使用vctrs::vec_interleave

library(vctrs)
vec_interleave(vec, paste0(vec, "_2"))
#[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

或者,在每隔一个元素中添加"_2"

paste0(rep(vec, each = 2), c("", "_2"))
#[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"
qkf9rpyu

qkf9rpyu3#

使用sprintf将原始字符串和修改后的字符串连接在一起,并添加一个符号,确保该符号不会出现在原始字符串中,然后拆分它们并使用unlist

unlist(strsplit(sprintf("%s@%s_2", vec, vec), "@"))
[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"
0h4hbjxa

0h4hbjxa4#

一个选项可能是每秒rep vec和replace

replace(rep(vec, each=2), c(FALSE, TRUE), paste0(vec, "_2"))
#[1] "D"   "D_2" "A"   "A_2" "B"   "B_2" "A"   "A_2"

相关问题