Separar una columna en varias columnas, cuando son datos especiales

Buen día,

Como logro separa una columna en varias columnas cuando los datos que contiene la columna inicial está separado por un guión bajo y no todos los datos cuentan con el mismo número de guiones.

Aquí un extracto de mi tabla, con la columna VACUNA:

VACUNA
opv_2_1a4_tar
neumococo23_1_otraedad_tar_enf
sr_1_5a14_tar
hepatitisb_2_especial_tar_vih

Si se dan cuenta, en la columna VACUNA en el primer caso el dato (opv_2_1a4_tar) está separado por 3 guiones bajos, en el segundo caso el dato (neumococo23_1_otraedad_tar_enf) está separado por 4 guiones bajos y así con el resto de casos.

Al utilizar la función separete me arroja un error, que es el siguiente
Cuando uso la función SEPARATE me emite un error:

Warning message:
Expected 5 pieces. Missing pieces filled with NA in 11 rows [1, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36].

You are not getting an Error, you are getting a Warning (advertencia) and separate() is filling the missing values with NA. You can suppress the Warning with

separate(..., fill = "right")

For example:

DF <- data.frame(Vacuna = c("VACUNA",
"opv_2_1a4_tar",
"neumococo23_1_otraedad_tar_enf",
"sr_1_5a14_tar",
"hepatitisb_2_especial_tar_vih"))
library(tidyr)
DF |> separate("Vacuna", into = c("A","B","C","D","E"))
#> Warning: Expected 5 pieces. Missing pieces filled with `NA` in 3 rows [1, 2,
#> 4].
#>             A    B        C    D    E
#> 1      VACUNA <NA>     <NA> <NA> <NA>
#> 2         opv    2      1a4  tar <NA>
#> 3 neumococo23    1 otraedad  tar  enf
#> 4          sr    1     5a14  tar <NA>
#> 5  hepatitisb    2 especial  tar  vih
DF |> separate("Vacuna", into = c("A","B","C","D","E"), fill = "right")
#>             A    B        C    D    E
#> 1      VACUNA <NA>     <NA> <NA> <NA>
#> 2         opv    2      1a4  tar <NA>
#> 3 neumococo23    1 otraedad  tar  enf
#> 4          sr    1     5a14  tar <NA>
#> 5  hepatitisb    2 especial  tar  vih

Created on 2023-10-20 with reprex v2.0.2

1 Like

Excelente, muchas gracias!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.