Home > other >  Is there an r function that will repeat a number, limited by ";" for x number of times
Is there an r function that will repeat a number, limited by ";" for x number of times

Time:12-16

I have a column of data, and I would like to create a new column with the value in column$input copied 'x' times and limited by ";"

x = 3

input = structure(list(input = c(67L, 24L, 72L, 3L)), row.names = c(NA, 
-4L), class = "data.frame")

output = structure(list(input = c(67L, 24L, 72L, 3L), output = c("67;67;67", 
"24;24;24", "72;72;72", "3;3;3")), row.names = c(NA, -4L), class = "data.frame")

I cannot for the life of me think of a simple way of doing this...

CodePudding user response:

Or using the tidyverse...

output <- input %>% 
  mutate(output = map_chr(input, ~paste(rep(., x), collapse = ";")))

CodePudding user response:

Simple, actually.

library(tidyverse)
input$output = map_chr(input$input, ~ paste(rep(.x, x), collapse=";"))

or, if you really, really prefer to do it with dplyr

input <- input %>% rowwise() %>% 
           mutate(output = paste(rep(input, 3), collapse=";"))

Aaaand with base R:

output$input <- sapply(input$input, \(x) paste(rep(x, 3), collapse=";")) 
  • Related