12

I have a very strange problem concerning the ifelse function: it does not return a factor (as I want) but something like the position of the factor.

The dataset I use can be downloaded here.

What I want

..is to make a new column in df that contains the name of the country IF that country belongs to the top 12 most frequent countries (in the column "answer"). Else it should contain "Other"

What I did

... is

  • Create a list with the most frequent country names using as.data.frame(summary.. etc) ##this works
  • The TRUE part of the function matches df$col value with this list using %in% ##this works also
  • Return value if TRUE should be the factor (a country name) in that

However

... R returns something really strange: it returns the position of the factor level (between 1 and 181) for the top 10 countries, and "Other" for the others (which is ok). It is this line that returns the wrong value:

        aDDs$answer, ## then it should be named as aDDs$answer **THIS IS THE PROBLEM**

The code I used:

## create a list with most frequent country names
temp <- row.names(as.data.frame(summary(aDDs$answer, max=12))) # create a df or something else with the summary output.
colnames(temp)[1]="freq"
"India" %in% temp #check if it works (yes)

## create new column that filters top results
aDDs$top <- ifelse(
        aDDs$answer %in% temp, ## condition: match aDDs$answer with row.names in summary df 
        aDDs$answer, ## then it should be named as aDDs$answer **THIS IS THE PROBLEM**
        "Other" ## else it should be named "Other"
      )

View(aDDs)

PS. This is a follow-up question to this one, because it is somewhat different, and may need a separate question.

3 Answers 3

21

The field answer is factor, hence your function returns number (level of factor).

What you need to do is:

aDDs$answer <- as.character(aDDs$answer)

and then it works.

3
  • yeah!!! pfffff. Incredible.. This cost me tooooo much time already, and I was playing around with as.character before, but probably put it on the wrong place. Thanks a lot! Commented Feb 6, 2014 at 14:02
  • 3
    This is why R makes me so mad sometimes. Why would I want to pass a factor and get the index back? it's IF ELSE! the most basic thing in programming! you also don't get any warning about it.
    – Omri374
    Commented Mar 25, 2015 at 12:15
  • @Omri374 there is actually a warning, it's just not obvious, in ?ifelse "ifelse() strips attributes. This is important when working with Dates and factors"
    – Scransom
    Commented Jun 19, 2017 at 0:25
3

That's because you have a factor:

ifelse(c(T, F), factor(c("a", "b")), "other")
#[1] "1"     "other"

Read the warning in help("ifelse"):

The mode of the result may depend on the value of test (see the examples), and the class attribute (see oldClass) of the result is taken from test and may be inappropriate for the values selected from yes and no.

Sometimes it is better to use a construction such as

(tmp <- yes; tmp[!test] <- no[!test]; tmp) , possibly extended to handle missing values in test.

0

Modify your ifelse as follows

aDDs$top <- ifelse(
        aDDs$answer %in% temp, ## condition: match aDDs$answer with row.names in summary df 
        levels(aDDs$answer)[aDDs$answer], ## then it should be named as aDDs$answer **THIS IS THE PROBLEM**
        "Other" ## else it should be named "Other"
      )

Notice the function levels and the box brackets. Levels knows how many factors are their and their index. So, essentially what we are saying is give me the the factor value corresponding to some index value.

Sample demo:

topCountries<-as.factor(c("India", "USA", "UK"))
AllCountries<-as.factor(c("India", "USA", "UK", "China", "Brazil"))
myData<-data.frame(AllCountries)
myData

myData$top<-ifelse(
        myData$AllCountries %in% topCountries,
        levels(myData$AllCountries)[myData$AllCountries], 
        "Other" 
      )


myData

the top column in myData will have "Other" for China & Brazil. For rows where Allcountries in {India, USA, UK} it will return their respective values i.e., {India, USA, UK} . Without the use of levels it will return "Other" and factor index values for {India, USA, UK} .

3
  • This is overly complicated. Just use as.character.
    – Roland
    Commented Feb 6, 2014 at 13:52
  • @Rolan, sure. What if the user wants to keep the top column as factor? does using as.character make the column top of type character?
    – user1509107
    Commented Feb 6, 2014 at 13:55
  • Never mind, in either case top is stored as character.
    – user1509107
    Commented Feb 6, 2014 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.