Home > Software design >  Change format of column to "XXX" by using str_pad in string package
Change format of column to "XXX" by using str_pad in string package

Time:07-24

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:

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 %>%.

CodePudding user response:

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
  • Related