Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ifelse is erroneously replacing text with integers

Tags:

r

I have some data that I'm working with from a Udacity course (Link: Reddit Survey Responses). I'm trying to simplify the Employment Status variable by replacing any multi-word values with single word alternates using

RS$employment.status <- ifelse(RS$employment.status == "Not employed,  but looking for work",
                               "Unemployed", RS$employment.status)

However, when I run the code any values that aren't supposed to be replaced are replaced with numeric values. Given that the else case is to use the field's value, I'm not sure why the text isn't preserved as-is.

Here's a screenshot of the initial data enter image description here

And the after enter image description here

So if anyone could point out

  1. why the substitution is being made when it doesn't look like it should be;
  2. what would be the correct way to accomplish what I'm trying to achieve;

it would be much appreciated.

like image 641
JMichael Avatar asked Dec 05 '25 17:12

JMichael


1 Answers

The problem is that this variable is set as a Factor, so to fix your problem you can either add this argument when you read your data stringsAsFactors = FALSE or you could do this:

  RS$employment.status <- ifelse(RS$employment.status == "Not employed, but looking for work", 
"Unemployed", as.character(RS$employment.status))
like image 172
Andrelrms Avatar answered Dec 08 '25 08:12

Andrelrms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!