Reputation: 41
how can I shorten this vector without having to type every single one of the elements? I want to use these as labels on a barplot, but I am finding the code so long. Is there any simple and shorter way? Thanks
I tried paste("1", letters[1:6], sep = "")
but falling short as you can see and I don't know how to lengthen it.
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")
Upvotes: 1
Views: 213
Reputation: 7724
For variable lenght of letters you can do
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"
For a fixed length of numbers and letters you can use:
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
is short for paste(..., sep = "")
, rep
repeats the argument 1:5
6 times each, letters[1:6]
is repeated automatically so that the length matches the length of rep(1:5, each = 6)
.
Upvotes: 2
Reputation: 39717
You can use rep
and sequence
to produce the desired vector:
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"
Upvotes: 1
Reputation: 50718
As an alternative avoiding letters
, what about making use of decimal to hexadecimal conversion?
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"
The flag "%x"
prints a decimal integer as a hexadecimal integer; the set of elements corresponds to the numbers 16 * i + 10
, 16 * i + 11
, ..., 16 * i + 15
for i
from 1 to 4.
Upvotes: 0
Reputation: 389175
Here is another way using 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" .....
Upvotes: 1