# Convert decimal into chr or factor (within decimal range)

So in my data.frame "whr2021", I have a variable called "Social support" that is the national average of the binary responses (either 0 or 1) to the question “If you were in trouble, do you have relatives or friends you can count on to help you whenever you need them, or not?”. So this variable takes decimal values between 0 and 1.

I would like to have it is a factor() value so it is easier to analyse it. I would like it to take the value "no" if the value is under 0.5 and "yes" if it is over or equal to 0.5. So basically something like that (but this doesn't work so please correct me):

``````whr2021\$`Social support` <- factor(whr2021\$`Social support`, levels = c(<0.5,>=0.5), labels = c("Non", "Oui"))
``````

You can enclose it inside an `ifelse()` statement to achieve what you want to do:

``````my_vec <- sample(seq.default(0,1,0.1),10)
my_vec
#>  [1] 1.0 0.7 0.1 0.8 0.9 0.0 0.6 0.5 0.3 0.4

my_vec <- factor(ifelse(my_vec < 0.5, "Non", "Oui"))
my_vec
#>  [1] Oui Oui Non Oui Oui Non Oui Oui Non Non
#> Levels: Non Oui
``````

Created on 2023-02-17 with reprex v2.0.2

The reason why it's not working is your levels vector. c(`<0.5, >=0.5)` simply produces an error, since you aren't comparing anything inside `c()` with your relational signs. But if you instead check the condition within an `ifelse()` statement beforehand and initialize the factor on the new `chr` vector, it will work like you can see above.

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.