R ifelse is erroneously replacing text with integers

若如初见. 提交于 2021-02-10 10:44:35

问题


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

And the after

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.


回答1:


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))


来源:https://stackoverflow.com/questions/31951478/r-ifelse-is-erroneously-replacing-text-with-integers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!