Mutate variable with specified length

# toy data
df  <- tibble(v1 = c("123567", "123456789"),
       v2 = c("7.54321", "87.54321"))
# A tibble: 2 x 2
  v1        v2      
  <chr>     <chr>   
1 123567    7.54321 
2 123456789 87.54321

How do I mutate v1 and v2 with specified length?

  • length of v1 will be 20; add spaces to the right
  • length of v2 will be 10; add spaces to the left
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(stringr)

df  <- tibble(v1 = c("123567", "123456789"),
              v2 = c("7.54321", "87.54321"))

mutate(df,
       
       # pad the strings
       v1 = str_pad(v1, width = 20, "right"),
       v2 = str_pad(v2, width = 10, "left"),
       
       # check if it worked
       v1len = str_length(v1),
       v2len = str_length(v2))
#> # A tibble: 2 x 4
#>   v1                     v2           v1len v2len
#>   <chr>                  <chr>        <int> <int>
#> 1 "123567              " "   7.54321"    20    10
#> 2 "123456789           " "  87.54321"    20    10

Created on 2022-01-10 by the reprex package (v2.0.1)

1 Like

@JackDavison Many thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.