Add a number prefix to a regular expression in r

Hi,

I have a list contains characters with different lengths, I want to add prefix for characters with specific length.

library(tidyverse)

a = list("20013536", "20017954","19618","18114")
a

[[1]]
[1] "20013536"

[[2]]
[1] "20017954"

[[3]]
[1] "19618"

[[4]]
[1] "18114"

I want to add the numerical prefix "200" to the third and fourth elements of the list.

Thank you in advance.

Regards,
Mohamed.

Is this conditional to the length of the string ? Like if only 5 digits, add 200 before ?

a = c("20013536", "20017954","19618","18114")


# iterate
purrr::map_chr(a, ~{
  if (nchar(.x) == 5) paste0("200", .x) else .x
})
#> [1] "20013536" "20017954" "20019618" "20018114"

# vectorise
dplyr::if_else(nchar(a) == 5, paste0(200, a), a)
#> [1] "20013536" "20017954" "20019618" "20018114"

Created on 2020-08-20 by the reprex package (v0.3.0.9001)

If you can create a function pad_if_only_five() to apply each time you need.

2 Likes

Thanks cderv,

the code worked well as a is a vector, when I tried to apply the code on a list, it through an erro

Error: unexpected '}' in:
" + if (nchar(.x) == 5) paste0("200", .x) else .x
+ }"

I am trying to use the code with list, even with lapply, but I'm not able to fix it.

Thank you in advance for your support.

Regards,
Mohamed.

It works with list also,

a = list("20013536", "20017954","19618","18114")


# iterate
purrr::map_chr(a, ~{
  if (nchar(.x) == 5) paste0("200", .x) else .x
})
#> [1] "20013536" "20017954" "20019618" "20018114"

Created on 2020-08-21 by the reprex package (v0.3.0)

You seem to have a syntax error in your code

1 Like

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