Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "for" loop in r with a table

Tags:

r

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)
  
}
like image 619
Moises T Avatar asked Apr 06 '26 00:04

Moises T


1 Answers

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" 
like image 71
ThomasIsCoding Avatar answered Apr 08 '26 15:04

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!