Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How replace just leading number for a string where those characters appear also as unit

I have the following vector

vector <- c(31, 41, 51, 61, 32, 42, 52, 62, 33, 43, 53, 63,
            34, 44, 54, 64, 35, 45, 55, 65, 36, 46, 56, 66)

I would like just to replace the leading number without convert that number when it is found as unit digit

str_replace_all(vector, c('3' = 'Air', '4' = 'Car',
                          '5' = 'Polluted', '6' = 'Gas'))

The desired out is just is to use each final/unit digit as a marker meaning that for example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

wherever there is a 3(unit/digit), the code should convert it as:

'Air_(unit/digit)'

more clearly as:

#  [1] "Air_1"      "Car_1"      "Polluted_1"
#  [4] "Gas_1"      "Air_2"      "Car_2"     
#  [7] "Polluted_2" "Gas_2"      "Air_3"     
# [10] "Car_3"      "Polluted_3" "Gas_3"     
# [13] "Air_4"      "Car_4"      "Polluted_4"
# [16] "Gas_4"      "Air_5"      "Car_5"     
# [19] "Polluted_5" "Gas_5"      "Air_6"     
# [22] "Car_6"      "Polluted_6" "Gas_6" 

Would you suggest any quick way to do this? Thanks

>Solution :

Assuming we always have 2 digits, using arithmetic operators %% to get 1st digit and %/% to get remainder – the 2nd digit. Then paste all as desired:

paste(
  c('3' = 'Air', '4' = 'Car', '5' = 'Polluted', '6' = 'Gas')[
    as.character(vector %/% 10) ],
  vector %% 10, sep = "_")
#  [1] "Air_1"      "Car_1"      "Polluted_1"
#  [4] "Gas_1"      "Air_2"      "Car_2"     
#  [7] "Polluted_2" "Gas_2"      "Air_3"     
# [10] "Car_3"      "Polluted_3" "Gas_3"     
# [13] "Air_4"      "Car_4"      "Polluted_4"
# [16] "Gas_4"      "Air_5"      "Car_5"     
# [19] "Polluted_5" "Gas_5"      "Air_6"     
# [22] "Car_6"      "Polluted_6" "Gas_6" 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading