Following hours of searching for what should be simple I need help.
What I want to do: Ensure that all strings are padded to the same length of 26 characters in length.
Dataset:
library(stringr)
names <-
structure(list(
names = c(
"A",
"ABC",
"ABCDEFG",
"ABCDEFGHIJKLMNOP",
"AB",
"ABCDEFGHI",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"ABCDEFGHIJKL",
"ABCDEFGHIJKLMNOPQR",
"ABCDEFGHIJKLMNOP",
"ABCDEFGHIJKLMNO"
)
),
class = "data.frame",
row.names = c(NA,-11L))
Step 1: Find max character length and the number of spaces to pad:
max <- as.numeric(max(nchar(names$names)))
max
n <- as.numeric(nchar(names$names))
n
pad <- max - n
pad
#add columns to the dataset to check how many characters are to be padded for each name
names$max <- as.numeric(max(nchar(names$names)))
names$n <- as.numeric(nchar(names$names))
names$pad <- as.numeric(max - n)
Step 2: Pad
names$names <-
str_pad(names$names,
pad,
side = "right",
pad = "0")
But this approach doesn't appear to be working for me. Can someone point me in the right direction? I am getting different length strings:
names max n pad
1 A000000000000000000000000 26 1 25
2 ABC00000000000000000000 26 3 23
3 ABCDEFG000000000000 26 7 19
4 ABCDEFGHIJKLMNOP 26 16 10
5 AB0000000000000000000000 26 2 24
6 ABCDEFGHI00000000 26 9 17
7 ABCDEFGHIJKLMNOPQRSTUVWXYZ 26 26 0
8 ABCDEFGHIJKL00 26 12 14
9 ABCDEFGHIJKLMNOPQR 26 18 8
10 ABCDEFGHIJKLMNOP 26 16 10
11 ABCDEFGHIJKLMNO 26 15 11
Help would be greatly appreciated.