How to convert a chr variable to a factor variable to be able to identify levels

Hi,

I am new here, new to R and trying to find a community that could help me learn and grow.

I am currently following some Data Camps courses and simultaneously, I am trying to apply what i learn on my own data set from a future experiment that I will run.
I am trying to look at the levels of a variable but the output I obtain is NULL. My variable is chr and I am not sure how to transform it into a factor (as I think would help my NULL problem).
How do I convert a chr variable into a variable with factor?

Thank you for your help!

You can use as.factor() function

x <- c("a", "b", "c")
class(x)
#> [1] "character"
x <- as.factor(x)
class(x)
#> [1] "factor"
x
#> [1] a b c
#> Levels: a b c
levels(x)
#> [1] "a" "b" "c"

Created on 2019-03-06 by the reprex package (v0.2.1)

If you need more specific help, please make your questions with a minimal REPRoducible EXample (reprex)? A reprex makes it much easier for others to understand your issue and figure out how to help.

If you've never heard of a reprex before, you might want to start by reading this FAQ:

1 Like

Actually, I don't understand why "levels" don't work, it should work with chr data, right?

By definition a character vector doesn't has levels, if you want to know which unique values it has then you can use unique() function.

x <- c("a", "b", "c", "b", "a")
unique(x)
#> [1] "a" "b" "c"
1 Like

There is forcats package that might be of use for you to work with factors in a little bit more streamlined fashion.
For example, if you want to add new levels in factor vector, you can use fct_expand.

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.