0

Is there a way to label the "0"'s and "1"'s of my gender variable, as 'Female' and 'male' so that on plotting i get "gender=male" instead of gender=1. I would also be ok with Male and Female. I rarely work with R, so forgive my simple question.

I tried

gender2 = factor(gender2, levels = c("Female", "male")

but it gave me an error. it also made me uncomfortable that i couldn't specify the values for the ordering so make sure female is for coding 0 and male for coding 1.

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • 1
    You want `gender2 <- factor(gender2, levels=c(0,1), labels=c("Female", "Male"))` – DaveArmstrong Aug 08 '23 at 23:45
  • `data.frame(x = sample(0:1, 10, replace = TRUE)) |> mutate(x = factor(x, levels = c(0, 1), labels = c("Female", "Male")))` – Mark Aug 08 '23 at 23:45
  • A follow up Q- could we possibly remove the "variable= " part of the label in plot to make it cleaner? – Sakshi Tewari Aug 09 '23 at 00:08
  • Follow-ups are better posted as a new question, and please [include all required data and code](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) (as plain text) so we can reproduce the issue. – neilfws Aug 09 '23 at 00:12
  • @DaveArmstrong, please post as answer! If you're using `ggplot2` it sounds like you *might* be using something like `facet_wrap(..., labeller = label_both)`. If so, just drop the `labeller` argument – Ben Bolker Aug 09 '23 at 00:18

1 Answers1

0

The levels argument of factor should be the values in your existing variable. The labels argument is where you identify the words that should correspond with the existing values (in the same order). For example:

gender2 <- factor(gender2, levels=c(0,1), labels=c("Female", "Male")) 

The above would attach "Female" to the value 0 and "Male" to the value 1.

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
  • wanted to ask here, as i dont think this small query requires a new post- but does assignment "=" vs "<-" matter in making factor var? i get different results (yours works, while = nulls everything- table(variable) shows 0) – Sakshi Tewari Aug 09 '23 at 16:42
  • @SakshiTewari If you change the `<-` to `=`, it shouldn't matter. So, `gender2 = factor(gender2, ...)` should work. If you did it with `<-` first and then tried again with `=`, without reverting `gender2` back to its original values, you would get the result you describe. – DaveArmstrong Aug 09 '23 at 22:45