Reputation: 13
I have to add a specific number of character to the end of a value inside of a character vector under a condition - only for a certain columns. Each value has to have a fixed length of 5 characters, and if current value has less then 5, I have to add zeroes until it reaches maximum length - only if the first character of a value is a ie. letter "A".
input_vector <- c("ABC", "ZZX", "B", "AILK")
desirable_output <- c("ABC00", "ZZX", "B", "AILK0")
I am fairly new to the R world and I've only tried to write clunky code such as this one:
example_df<- data.frame(Col1= 1:11, Col2= 2:22, Col3= 3:33, Col4= 6:66)
index_values_of_columns<- c(1, 2, 4)
for (index_value in index_values_of_columns){
for (value in example_df[[index_value]]){
firstletter<-str_extract(value, "^.{1}")
if (!is.na(firstletter) && firstletter == "1"){
value<-str_pad(value, 5, side="right", pad="0")
}
}
}
Unfortunately, this doesn't change anything in a dataframe, although it doesn't generate any errors. Where I did wrong?
Upvotes: 1
Views: 150
Reputation: 4358
Here is a solution in base R
replace(input_vector,grep("A.",input_vector),strtrim(paste0(input_vector,"00000"),5)[grep("A.",input_vector)])
Upvotes: 0
Reputation: 51582
Try,
input_vector[substring(input_vector, 1, 1) == 'A'] <- str_pad(input_vector[substring(input_vector, 1, 1) == 'A'], 5, side = "right", pad = "0")
input_vector
#[1] "ABC00" "ZZX" "B" "AILK0"
Upvotes: 2