如何缩短此向量而不必键入每个元素?

时间:2019-10-03 09:35:47

标签: r

如何缩短此向量而不必键入每个元素?我想将它们用作条形图上的标签,但是发现代码的时间太长了。有没有简单而简短的方法?谢谢 我尝试了paste("1", letters[1:6], sep = ""),但您看到的却不够,而且我不知道如何延长它。

c("1a", "1b", "1c", "1d", "1e", "1f", "2a" ,"2b", "2c"  , "2d", "2e", "2f", "3a", "3b", "3c", "3d", "3e", "3f", "3g", "4a", "4b", "4c", "4d" , "4e", "4f", "4g", "5a", "5b", "5c", "5d")

4 个答案:

答案 0 :(得分:2)

对于可变长度的字母,您可以做

-w 1

对于固定长度的数字和字母,您可以使用:

l_len <- c(6, 6, 7, 7, 4)
num <- rep(seq_along(l_len), l_len)
let <- unlist(lapply(l_len, function(i) letters[seq_len(i)]))

paste0(num, let)
# [1] "1a" "1b" "1c" "1d" "1e" "1f" "2a" "2b" "2c" "2d" "2e" "2f" "3a" "3b" "3c" "3d" "3e" "3f" "3g" "4a" "4b" "4c" "4d" "4e" "4f" "4g" "5a" "5b" "5c" "5d"

paste0(rep(1:5, each = 6), letters[1:6]) # [1] "1a" "1b" "1c" "1d" "1e" "1f" "2a" "2b" "2c" "2d" "2e" "2f" "3a" "3b" "3c" "3d" "3e" "3f" "4a" "4b" "4c" "4d" "4e" "4f" "5a" "5b" "5c" "5d" "5e" "5f" paste0的缩写,paste(..., sep = "")重复参数rep 6次,1:5自动重复,以使长度与letters[1:6]

答案 1 :(得分:1)

这是使用outer

的另一种方法
fun <- function(x, y) paste0(x, y)
c(t(outer(1:5, letters[1:6], Vectorize(fun))))
#[1] "1a" "1b" "1c" "1d" "1e" "1f" "2a" "2b" "2c" "2d" "2e" "2f" "3a" "3b" .....

答案 2 :(得分:0)

您可以使用repsequence生成所需的向量:

x  <- c(6,6,7,7,4)
paste0(rep(seq_along(x), x), letters[sequence(x)])
# [1] "1a" "1b" "1c" "1d" "1e" "1f" "2a" "2b" "2c" "2d" "2e" "2f" "3a" "3b" "3c"
#[16] "3d" "3e" "3f" "3g" "4a" "4b" "4c" "4d" "4e" "4f" "4g" "5a" "5b" "5c" "5d"

答案 3 :(得分:0)

作为避免使用letters的替代方法,如何使用十进制到十六进制的转换?

unlist(Map(function(i) sprintf("%x", 16 * i + 10:15), 1:5))
#[1] "1a" "1b" "1c" "1d" "1e" "1f" "2a" "2b" "2c" "2d" "2e" "2f" "3a" "3b" "3c"
#[16] "3d" "3e" "3f" "4a" "4b" "4c" "4d" "4e" "4f" "5a" "5b" "5c" "5d" "5e" "5f"

标志"%x"将十进制整数打印为十六进制整数;元素集对应于16 * i + 10的数字16 * i + 1116 * i + 15,...,i从1到4。