0

I am ploting a dataframe into a shapefile map, but I need to repair a bunch of these codes.

Well. The map have 3 areas, identify by codes. 2 areas works good with the code, but all of the codes that start with 3 don´t work. These numbers need to start with 03.

So if I have 3002 in the dataframe, I need to repair to 03002. So It´s possible to make it from R? i need to put 0 where the data start by 3

This is a bit of my code: The column to repair with the 0 at the first 3´s its called "code2"

dfcsv1 <- read.csv("https://dadesobertes.gva.es/datastore/dump/e23bf332-be3e-4a3a-a07b-300db3d9a7be?bom=True", encoding = "UTF-8", header = TRUE, sep = ",")
colnames(dfcsv1) <- c("code", "code2", "Municipio", "PCR", "TasaPCR", "PCR14", "TasaPCR14", "Muertos", "TasaMuertos")
dfcsv1$TasaMuertos = as.numeric(gsub(",","\\.",dfcsv1$TasaMuertos))
dfcsv1$TasaPCR = as.numeric(gsub(",","\\.",dfcsv1$TasaPCR))
dfcsv1$TasaPCR14 = as.numeric(gsub(",","\\.",dfcsv1$TasaPCR14))


dfcsv1 <- dfcsv1 %>% 
  mutate(
    municipio = stringr::str_c(code2)
  )


mapa_df <- mapa_df %>% 
  left_join(
    y  = dfcsv1 %>% select(municipio, TasaPCR14),
    by = "municipio"
  )

thank you all in advance!

Raul
  • 139
  • 9

2 Answers2

1

And small example:

library(dplyr)

t <- tibble(CODE = c("4444", "55555","3333"))
t %>% 
  dplyr::mutate(CODE = case_when(nchar(CODE) == 3 ~ paste0("00", CODE),
                                 nchar(CODE) == 4 ~ paste0("0", CODE),
                                 TRUE ~ CODE))
DPH
  • 4,244
  • 1
  • 8
  • 18
1

A slightly more concise method would be stringr::str_pad: (Note the default is to 'pad' to the left. see ?str_pad)

library(dplyr)
library(stringr)

t <- tibble(CODE = c("4444", "55555","333"))
t %>% 
  dplyr::mutate(CODE = str_pad(CODE, 5, pad = '0'))
# A tibble: 3 x 1
  CODE 
  <chr>
1 04444
2 55555
3 00333
TTS
  • 1,818
  • 7
  • 16
  • Thank you so much! I have tried with: library(dplyr) library(stringr) dfcsv1 <- read.csv("https://dadesobertes.gva.es/datastore/dump/e23bf332-be3e-4a3a-a07b-300db3d9a7be?bom=True", encoding = "UTF-8", header = TRUE, sep = ",") colnames(dfcsv1) <- c("code", "code2", "Municipio", "PCR", "TasaPCR", "PCR14", "TasaPCR14", "Muertos", "TasaMuertos") dfcsv1 %>% dplyr::mutate(dfcsv1$code2 = str_pad(dfcsv1$code2, 5, pad = '0')) – Raul Nov 03 '20 at 23:43
  • dfcsv1 %>% dplyr::mutate(dfcsv1$code2 = str_pad(dfcsv1$code2, 5, pad = '0')) #but don´t works.. – Raul Nov 03 '20 at 23:44
  • 1
    `dfcsv1 <- dfcsv1 %>% dplyr::mutate(code2 = str_pad(code2, 5, pad = '0'))` Try that? – TTS Nov 03 '20 at 23:48
  • Thank you very much! Now works very good!! I am very new on R :) – Raul Nov 03 '20 at 23:52
  • 1
    When you're using the pipe (`%>%`) you don't need to indicate `dfcsv1$code2` because it already knows what dataframe you're modifying. It's the first part of that pipe stream, so you can just include the field `code2`. – TTS Nov 04 '20 at 00:00