Having two columns, one with numeric values and other with text labels that correspond exactly with the numeric values, how can I create a labelled column (<dbl+lbl>
), like the ones imported by the {haven}
package?
Example data:
structure(list(cut_comuna = c("16303", "8301", "13111", "13201",
"1101", "8110", "14204", "6101"),
comuna = c("Ñiquén", "Los Angeles",
"La Granja", "Puente Alto", "Iquique", "Talcahuano", "Río Bueno",
"Rancagua")),
row.names = c(NA, -8L),
class = c("tbl_df", "tbl", "data.frame"))
# A tibble: 8 × 2
cut_comuna comuna
<chr> <chr>
1 16303 Ñiquén
2 8301 Los Angeles
3 13111 La Granja
4 13201 Puente Alto
5 1101 Iquique
6 8110 Talcahuano
7 14204 Río Bueno
8 6101 Rancagua
Expected result, something like this:
comuna2
<dbl+lbl>
1 16303 [Ñiquén]
2 8301 [Los Angeles]
...
As an alternative you can create a named vector with no data loss.
library(dplyr)
df <- df %>%
mutate(comuna2 = `names<-`(cut_comuna, comuna))
df$comuna2
Ñiquén Los Angeles La Granja Puente Alto Iquique Talcahuano
"16303" "8301" "13111" "13201" "1101" "8110"
Río Bueno Rancagua
"14204" "6101"
There is no dbl+lbl
class but you can create a character variable combining two columns.
library(tidyverse)
df = structure(list(cut_comuna = c("16303", "8301", "13111", "13201",
"1101", "8110", "14204", "6101"),
comuna = c("Ñiquén", "Los Angeles",
"La Granja", "Puente Alto", "Iquique", "Talcahuano", "Río Bueno",
"Rancagua")),
row.names = c(NA, -8L),
class = c("tbl_df", "tbl", "data.frame"))
df %>% transmute(comuna2 = glue::glue("{cut_comuna} [{comuna}]"))
#> # A tibble: 8 × 1
#> comuna2
#> <glue>
#> 1 16303 [Ñiquén]
#> 2 8301 [Los Angeles]
#> 3 13111 [La Granja]
#> 4 13201 [Puente Alto]
#> 5 1101 [Iquique]
#> 6 8110 [Talcahuano]
#> 7 14204 [Río Bueno]
#> 8 6101 [Rancagua]
Created on 2024-07-17 with reprex v2.0.2
If you want to keep the original columns use mutate
instead of transmute
.
Note that your cut_comuna
variable is not numeric, but character. Anyway, it does not affect the results.