Home > Software design >  Use str_pad to mutate a new column
Use str_pad to mutate a new column

Time:07-24

I've have the following column/tibble:

Code
18
19
20
21
22
23
#With 200 more rows

I would like to create this tibble:

Muncode   Code
 0118      18
 0119      19
 0120      20
 0121      21
 0122      22
 0123      23
#With 200 more rows

I belive mutate() together with str_pad would create the desired tibble. Any ideas?

I've tried below code but it didn't work.

mutate(Muncode(str_pad($code, 4, '0', STR_PAD_LEFT))

CodePudding user response:

Like this?

df %>% mutate(Muncode = sprintf("d", Code   100L))
#  Code Muncode
#1   18    0118
#2   19    0119
#3   20    0120
#4   21    0121
#5   22    0122
#6   23    0123

CodePudding user response:

In order to use str_pad you'll need to beware of the arguments it takes and the order if you don't specify them:

string A character vector.

width Minimum width of padded strings.

side Side on which padding character is added (left, right or both).

pad Single padding character (default is a space).

Ref: [Package stringr version 1.4.0 Index]

You might as well need to tell mutate what data to use, and what column to create. I.e.:

library(dplyr)
library(stringr)

dat <- tibble(Code = 18:23)

dat |>
  mutate(Muncode = str_pad(string = Code,
                           width = 4,
                           side = "left",
                           pad = 0))

Output:

# A tibble: 6 × 2
   Code Muncode
  <int> <chr>  
1    18 0018   
2    19 0019   
3    20 0020   
4    21 0021   
5    22 0022   
6    23 0023   

Update: If you want to pad with 01 and not 00 you could use paste0 or sprintf as suggeseted in the comments. Or to stay within stringr, you could use str_c:

dat |>
  mutate(Muncode = str_c("01", Code))
# A tibble: 6 × 2
   Code Muncode
  <int> <chr>  
1    18 0118   
2    19 0119   
3    20 0120   
4    21 0121   
5    22 0122   
6    23 0123   
  •  Tags:  
  • r
  • Related