snt
May 29, 2018, 3:51pm
1
I have a field where the levels are broken down as below:
levels(demo$age)
"18 to 24 years old" "25 to 34 years old" "35 to 44 years old" "45 to 54 years old" "55 to 64 years old" "65 to 74 years old" "75 years old or older"
How can I change the levels to
"Total " "18 to 24 years old" "25 plus".
mara
May 29, 2018, 3:55pm
2
Check out the fct_collapse()
function in {forcats}
*n.b. "Total" wouldn't be a level if it encompasses everything.
library(forcats)
fct_count(gss_cat$partyid)
#> # A tibble: 10 x 2
#> f n
#> <fct> <int>
#> 1 No answer 154
#> 2 Don't know 1
#> 3 Other party 393
#> 4 Strong republican 2314
#> 5 Not str republican 3032
#> 6 Ind,near rep 1791
#> 7 Independent 4119
#> 8 Ind,near dem 2499
#> 9 Not str democrat 3690
#> 10 Strong democrat 3490
partyid2 <- fct_collapse(gss_cat$partyid,
missing = c("No answer", "Don't know"),
other = "Other party",
rep = c("Strong republican", "Not str republican"),
ind = c("Ind,near rep", "Independent", "Ind,near dem"),
dem = c("Not str democrat", "Strong democrat")
)
fct_count(partyid2)
#> # A tibble: 5 x 2
#> f n
#> <fct> <int>
#> 1 missing 155
#> 2 other 393
#> 3 rep 5346
#> 4 ind 8409
#> 5 dem 7180
Created on 2018-05-29 by the reprex package (v0.2.0).
snt
May 29, 2018, 4:45pm
4
So I am doing this using reactive in Shiny.
gender_levels <- reactive({
fct_collapse(with_demo_vars()$gender,
Total = c("Male", "Female"),
Male = c("Male"),
Female = c("Female"))
print(gender_levels)
})
output$choose_gender <- renderUI({
checkboxGroupInput(
"selected_gender",
"Gender",
choices = fct_count(gender_levels),
selected = fct_count(gender_levels)
)
})
I get the following error :
f
must be a factor (or character vector).
mara
May 29, 2018, 5:02pm
5
Hmm, as mentioned, I don't think Total is actually a case of fct_collapse()
, but there are probably elements of what's going on that are related to Shiny. So, I'd recommend you move this over to the #shiny category so you can get more knowledgeable help!
When changing the category for a question, you will not lose anything. The thread stays the same. All you need to do is click the pencil icon next to the post title, and then use the dropdown to select a different category.
[image]
If you can edit this topic's category, note the pencil icon.
[image]
[image]
Based on replies by @mara