用字符串元素制作向量

我想使用字符串元素制作以下向量:

L1 L1 L2 L2 L3 L3 L4 L4 L5 L5 L6 L6 L7 L7 L7 L8 L8 L9 L9 L10 L10

为了制作此向量,我使用了以下代码:

rep(c(“ L1”,“ L1”,“ L2”,“ L2”,“ L3”,“ L3”,“ L4”,“ L4”),2)

但是我认为代码比我的代码短(更容易或更简单)。你有什么主意吗?

评论
Ken
Ken

您可以使用:

paste0("L", sort(rep(c(1:10), 2)))

 [1] "L1"  "L1"  "L2"  "L2"  "L3"  "L3"  "L4"  "L4"  "L5"  "L5"  "L6"  "L6" 
[13] "L7"  "L7"  "L8"  "L8"  "L9"  "L9"  "L10" "L10"

The idea here is to use rep to generate the sequence 1:10 twice. Then, we sort ascending to force 1, 1, 2, 2, ..., 10, 10.

点赞
评论
云想衣裳
云想衣裳

尝试:

rep(paste0("L", 1:10), each=2)
#>  [1] "L1"  "L1"  "L2"  "L2"  "L3"  "L3"  "L4"  "L4"  "L5"  "L5"  "L6"  "L6" 
#> [13] "L7"  "L7"  "L8"  "L8"  "L9"  "L9"  "L10" "L10"
点赞
评论
果粒、橙
果粒、橙

一种选择是:

paste0("L", rep(1:10, each = 2))

 [1] "L1"  "L1"  "L2"  "L2"  "L3"  "L3"  "L4"  "L4"  "L5"  "L5"  "L6"  "L6"  "L7" 
[14] "L7"  "L8"  "L8"  "L9"  "L9"  "L10" "L10"
点赞
评论