Reputation: 150
I got a problem which I just don't understand.
I would like to put together strings, depending on the number of characters:
the vector c("1", "23", "302", "2004")
should be transformed into c("1900001", "1900023", "1900302", "1902004")
.
Therefore I used this code:
test <- c("1", "23", "302", "2004")
fun_function <- function(test){
if(nchar(test == 4)){
str_c("190",test, sep="")
} else {
if(nchar(test == 3)){
str_c("1900", test, sep="")
} else{
if(nchar(test == 2)){
str_c("19000", test, sep="")
} else{
if(nchar(test == 1)){
str_c("190000", test, sep="")
}
}
}
}
}
res <- map(test,
~fun_function(.x)) %>%
unlist()
However, instead of getting c("1900001", "1900023", "1900302", "1902004")
I get c("1901", "19023", "190302", "1902004")
.
Now, why I get that vector? If I'm using this function for a single case, it works:
nchar("1") == 1
str_c("190000", "1", sep="")
So, where is the problem? I just don't understand the reason for my outcome. Can someone help me with this? I also tried a For Loop using the same logic, but that does not work either.
Upvotes: 0
Views: 106
Reputation: 2718
You're condition checking in the if statements is wrong. Its nchar(test) == 4
, not nchar(test == 4)
But the str_pad
function from stringr
is a much more concise way to approach the problem. First I pad with zeros to 5 digits, and then paste a '19' onto each.
test2 <- str_pad(test, 5, 'left', pad = '0')
test3 <- paste0('19', test2)
test3
[1] "1900001" "1900023" "1900302" "1902004"
Upvotes: 2