Paste and repeat a character value number of time specified by the column and create a new column in r

Viewed 190

I have df I would like to create a new column that is code repeated by frequency concatenated by and underscore if frequency is 3 and code is 1003 output would be "1003_1003_1003"

df<-data.frame( "userid" = stri_rand_strings(5,12), "code" = c("1001", "1002", "1003", "1004", "1005"), "frequency" = seq.int(1:30) )
head(df)
        userid: code frequency
1 FVddk0XxpgWf 1001         1
2 DDOn4sz4ndwk 1002         2
3 Mzhy6JdXHQSj 1003         3
4 eHFd8BCO9L4A 1004         4
5 nyl9BADGmlun 1005         5
6 FVddk0XxpgWf 1001         6

I would like to have code pasted by the number of times show in frequency separated by an underscore in a new column...so row 2 would have the new_column = "1002_1002"

I have tried :

df$new_column<-paste(rep(df$code, df$frequency), sep  = "_"))
2 Answers

here, strrep could be used

library(dplyr)
library(stringr)
df %>% 
     mutate(new_column = trimws(strrep(str_c(code, "_"),
          frequency), whitespace = "_"))

The strrep option by @akrun is very efficient. Here is another option with base R

transform(
  df,
  new = mapply(function(x, y) paste0(rep(x, y), collapse = "_"), code, frequency)
)

or tapply (thank @akrun's comment)

within(
  df,
  new = tapply(rep(code, frequency), rep(seq_along(code), frequency), FUN = paste, collapse = "_")
)
Related