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

Add character to specific value in rows by condition

lets say we have following data:

    df1 = data.frame(cm= c('10129', '21120', '123456','345239'), 
                     num=c(6,6,6,6))

 >  df1

cm      num
10129    6
21120    6
123456   6
345      4

as you see the length of some boxes in the cm column is 6 digits and some of 5 digits. I want to code the following: if the number of digits in the cm column is less than number in num column, add 0 value in the front to get the given output:

cm      num
010129    6
021120    6
123456    6
0345      4

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 :

You can use str_pad

library(tidyverse)

df1 %>% mutate(cm = str_pad(cm, num, "left", "0"))
#>       cm num
#> 1 010129   6
#> 2 021120   6
#> 3 123456   6
#> 4   0345   4

Created on 2022-04-13 by the reprex package (v2.0.1)


Input Data

df1 <- data.frame(cm  = c('10129', '21120', '123456','345'), num = c(6,6,6,4))

df1
#>       cm num
#> 1  10129   6
#> 2  21120   6
#> 3 123456   6
#> 4    345   4
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