A test dataset
structure(list(numero_certificado = c("1234", "5678"
), sitio_defuncion = c("HOSPITAL/CLINICA", "HOSPITAL/CLINICA"
), tipo_defuncion = c("NO FETAL", "NO FETAL"), fecha_defuncion = structure(c(1635861000,
1635874800), tzone = "", class = c("POSIXct", "POSIXt")), tipo_documento_fallecido = c("REGISTRO CIVIL",
"CEDULA DE CIUDADANIA"), documento_fallecido = c("1111",
"2222")), row.names = c(NA, -2L), class = c("tbl_df", "tbl",
"data.frame"))
I would like to be able to
Add singles quotes (') to each element of the entire dataset
Add singles quotes (') to all elements in specific columns based on index, as some data will be numeric or date and not string
structure(list(numero_certificado = c("'1234'", "'5678'" ), sitio_defuncion = c("'HOSPITAL/CLINICA'", "'HOSPITAL/CLINICA'" ), tipo_defuncion = c("'NO FETAL'", "'NO FETAL'"), fecha_defuncion = structure(c(1635861000, 1635874800), tzone = "", class = c("POSIXct", "POSIXt")), tipo_documento_fallecido = c("'REGISTRO CIVIL'", "'CEDULA DE CIUDADANIA'"), documento_fallecido = c("'1111'", "'2222'")), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"))
CodePudding user response:
We may use sQuote by looping across the columns (everything() - if all the columns needs to be changed or for selected columns use one of the select_helpers i.e. here if we need to remove the fecha_defuncion, prefix with -) of the data
library(dplyr)
df1 <- df1 %>%
mutate(across(-fecha_defuncion, sQuote, FALSE))
-output
df1
# A tibble: 2 × 6
numero_certificado sitio_defuncion tipo_defuncion fecha_defuncion tipo_documento_fallecido documento_fallecido
<chr> <chr> <chr> <dttm> <chr> <chr>
1 '1234' 'HOSPITAL/CLINICA' 'NO FETAL' 2021-11-02 08:50:00 'REGISTRO CIVIL' '1111'
2 '5678' 'HOSPITAL/CLINICA' 'NO FETAL' 2021-11-02 12:40:00 'CEDULA DE CIUDADANIA' '2222'
Also as @KonradRudolph mentioned in the comments, if the sQuote depends on the locale, another option is either glue or paste or sprintf
df1 <- df1 %>%
mutate(across(-fecha_defuncion, ~sprintf("'%s'", as.character(.))))
