I have the following database
library(data.table)
dt <- data.table(prod= c("AAAA","BBBB","CCCC"),
version= c(4,3,5))
And I want to obtain this
AAAA1
AAAA2
AAAA3
AAAA4
BBBB1
BBBB2
BBBB3
CCCC1
CCCC2
CCCC3
CCCC4
CCCC5
Now I have the following code, but it only works for the AAAA but not for the rest
list <- c()
for(i in 1:dt$version){
list[[i]] <- paste0(dt$prod,i)
}
A base R option using rep + sequence + paste0
> with(dt,paste0(rep(prod,version),sequence(version)))
[1] "AAAA1" "AAAA2" "AAAA3" "AAAA4" "BBBB1" "BBBB2" "BBBB3" "CCCC1" "CCCC2"
[10] "CCCC3" "CCCC4" "CCCC5"
or mapply + paste0 + seq
> with(dt, unlist(mapply(function(x,y) paste0(x,seq(y)), prod,version)))
AAAA1 AAAA2 AAAA3 AAAA4 BBBB1 BBBB2 BBBB3 CCCC1 CCCC2 CCCC3
"AAAA1" "AAAA2" "AAAA3" "AAAA4" "BBBB1" "BBBB2" "BBBB3" "CCCC1" "CCCC2" "CCCC3"
CCCC4 CCCC5
"CCCC4" "CCCC5"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With