I'm building a tibble which has some factors. I then need to add one more row manually but this changes all the factors to characters which was unexpected. How can I retain the factors in this code? This reprex all using built-in R data. I really want for REGION and DIVISION to be factors.
library(tibble)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(forcats)
state_ds <- tibble(
state=state.abb,
region.orig=state.region,
division.orig=state.division
) %>%
mutate(
REGION=fct_recode(region.orig, Midwest="North Central") %>%
fct_relevel(c("Northeast", "Midwest", "South", "West")),
DIVISION=fct_relevel(division.orig, c("East North Central", "West North Central"), after=2)
)
state_ds
#> # A tibble: 50 × 5
#> state region.orig division.orig REGION DIVISION
#> <chr> <fct> <fct> <fct> <fct>
#> 1 AL South East South Central South East South Central
#> 2 AK West Pacific West Pacific
#> 3 AZ West Mountain West Mountain
#> 4 AR South West South Central South West South Central
#> 5 CA West Pacific West Pacific
#> 6 CO West Mountain West Mountain
#> 7 CT Northeast New England Northeast New England
#> 8 DE South South Atlantic South South Atlantic
#> 9 FL South South Atlantic South South Atlantic
#> 10 GA South South Atlantic South South Atlantic
#> # ℹ 40 more rows
state_ds %>%
add_row(tibble_row(state="DC", REGION="South", DIVISION="South Atlantic"))
#> # A tibble: 51 × 5
#> state region.orig division.orig REGION DIVISION
#> <chr> <fct> <fct> <chr> <chr>
#> 1 AL South East South Central South East South Central
#> 2 AK West Pacific West Pacific
#> 3 AZ West Mountain West Mountain
#> 4 AR South West South Central South West South Central
#> 5 CA West Pacific West Pacific
#> 6 CO West Mountain West Mountain
#> 7 CT Northeast New England Northeast New England
#> 8 DE South South Atlantic South South Atlantic
#> 9 FL South South Atlantic South South Atlantic
#> 10 GA South South Atlantic South South Atlantic
#> # ℹ 41 more rows
Created on 2024-12-30 with reprex v2.1.1