Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
828 views
in Technique[技术] by (71.8m points)

if statement - R: ifelse function returns vector position instead of value (string)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...