0

I am trying to add a new column to a data frame as follows:

stateFrame$cgroup <- ifelse(stateFrame$Freq >= 11 & 
                   stateFrame$Freq < 83, "Other",stateFrame$city)

So, I want if the value of frequency in the row is between 11 and 83, the new column must be assigned Other, else it should keep the same value as exists in another column city (stateFrame$city).

It works fine for adding value as other but for all other cases, a row number corresponding to the data frame is assigned as shown below:

enter image description here

What could be the reason for this? Am I missing anything?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • Can you add `str(stateFrame)` to your question? – markus Feb 24 '18 at 20:41
  • 1
    Google "ifelse factor coerce R site:stackoverflow.com". E.g. [How does R's ifelse work with character data?](https://stackoverflow.com/questions/10761686/how-does-rs-ifelse-work-with-character-data) and a more thorough explanation in [this answer](https://stackoverflow.com/a/6669237/1851712) – Henrik Feb 24 '18 at 20:41

1 Answers1

1

I think your "no" input in ifelse() should be a vector and yours is most likely factor. Use as.vector(stateFrame$city) as follows:

stateFrame$cgroup <- ifelse(stateFrame$Freq >= 11 & 
                   stateFrame$Freq < 83, "Other",as.vector(stateFrame$city))

Edit To be more precise Factor is stored as vector of integers with related character values. I think integers are returned in your code.