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

Change format of column to "XXX" by using str_pad in string package

I want to use the string str_pad function to make a column in desired format.

I’ve runned this code

gather(most_common, cnt, M:OG) %>% 
group_by(name) %>% 
slice(which.max(cnt)) %>%
arrange(code)

Which resulted in the following tibble:

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

Code      Name       most_common
32       Monkey        Africa
33       Wolf          Europe
34       Tiger         Asia
35       Godzilla      Asia
#With 1 234 more rows

I’m happy with my code above. However, because I’m going to merge this df later on. I need the code to be in format "XXX" / "032", as this:

Code      Name       most_common
032       Monkey        Africa
033       Wolf          Europe
034       Tiger         Asia
035       Godzilla      Asia
#With 1 234 more rows

string str_pad($code, $3, $0) I’ve runned this code, but it doesn’t work so I guess there is something wrong there. And should I run this code wherever I want in my chunk or by using %>%.

>Solution :

A possible solution:

library(tidyverse)

df <- read.table(text = "Code      Name       most_common
32       Monkey        Africa
33       Wolf          Europe
34       Tiger         Asia
35       Godzilla      Asia", header = T)

df %>% 
  mutate(Code = str_pad(Code, width = 3, pad = "0"))

#>   Code     Name most_common
#> 1  032   Monkey      Africa
#> 2  033     Wolf      Europe
#> 3  034    Tiger        Asia
#> 4  035 Godzilla        Asia
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