序列生成

发布于 2024-12-13 06:30:20 字数 350 浏览 3 评论 0原文

我很不好意思问这个简单的问题,但我无法弄清楚。

我有一个变量,

names <- c("M1", "K2L", "C2L", "N", "R_1_2", "CLA", "T123") # the real dataset has > 6000 valriables 

我想要双重命名并添加字母“a”和“b”,输出(也考虑顺序)将如下所示:

M1a, M1b, K2La, K2Lb, C2La, C2Lb, Na, Nb, R_1_2a, R_1_2b, CLAa, CLAb, T123a, T123b 

感谢您的帮助:

I am embrased to ask this simple question, but I could not figure it out.

I have a variable

names <- c("M1", "K2L", "C2L", "N", "R_1_2", "CLA", "T123") # the real dataset has > 6000 valriables 

I want to double names and add alphabets "a" and "b" and the output (consider order too) would look like the following:

M1a, M1b, K2La, K2Lb, C2La, C2Lb, Na, Nb, R_1_2a, R_1_2b, CLAa, CLAb, T123a, T123b 

Thanks for the help:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

带上头具痛哭 2024-12-20 06:30:20

repeach 参数一起使用可重复每个名称。然后使用paste将它们与后缀组合起来。

paste(rep(names, each = 2), c("a", "b"), sep = "")

让我们以慢动作再看一遍:

suffixes <- c("a", "b")  # or letters[1:2] if you're feeling fancy
n_suffixes <- length(suffixes)
repeated_names <- rep(names, each = n_suffixes)
final_names <- paste(repeated_names, suffixes, sep = "")

使用外部产品的花式替代版本:

as.vector(t(outer(names, suffixes, paste, sep = "")))

虽然我认为这更多是为了炫耀,因为它的可读性较差。

Use rep with the each argument to repeat each name. Then use paste to combine them with the suffix.

paste(rep(names, each = 2), c("a", "b"), sep = "")

Let's look at that again in slow motion:

suffixes <- c("a", "b")  # or letters[1:2] if you're feeling fancy
n_suffixes <- length(suffixes)
repeated_names <- rep(names, each = n_suffixes)
final_names <- paste(repeated_names, suffixes, sep = "")

Fancy alternate version using outer products:

as.vector(t(outer(names, suffixes, paste, sep = "")))

Though I think this is more for showing off, since it's less readable.

烟沫凡尘 2024-12-20 06:30:20

使用 stringr 包的另一种解决方案

library(stringr)
str_c(rep(names, each = 2), c('a', 'b'))

Another solution using stringr package

library(stringr)
str_c(rep(names, each = 2), c('a', 'b'))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文