Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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=";")) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading