How to get a output with a table "Labels" where the label of each value is shown?

Dear community, :hugs:

I would love to receive you help by the following problem: I have a data frame (df) with the columns "ID" and "sex" (which refers to the single ID). Herefore, I have the values 1, 2, and 3 which stand for the labels female, male, and divers. I strive for a solution, where the code df$sex gives me an output where a table is shown, that is named "Labels" that gives me the "meaning" of each value (see picture).
This should appear additionally to the output where ALL objects of my data frame are shown with the values 1-3. But I don't need an output where, instead of the values 1-3, the labels female, male, or divers are shown.

I already tried some functions with "ordered" or "factor", but all of them were not appropriate for solving my issue.

PS: I am new to this community. I am sorry if I missed any details of your community rules.

Hi @raintwo
Welcome to the Posit/RStudio Community Forum.
You can simply create a new factor column in your dataframe where the levels are given the required labels:

df <- data.frame(ID=1:6, sex=c(1,2,3,3,2,1))
df$label <- factor(df$sex, labels=c("female","male","divers"))
#>   ID sex  label
#> 1  1   1 female
#> 2  2   2   male
#> 3  3   3 divers
#> 4  4   3 divers
#> 5  5   2   male
#> 6  6   1 female

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

1 Like

This topic was automatically closed 21 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.