Change ifelse as follows
aDDs$top <- ifelse( aDDs$answer %in% temp,
Pay attention to the levels function and square brackets. Levels know how many factors are their and their index. Thus, in essence, we are saying that this is a coefficient value corresponding to some index value.
Demo example:
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 a "different" for China and Brazil. For strings where Allcountries in {India, USA, UK} will return its corresponding values, that is {India, USA, UK}. Without using levels it will return “Other” and a factor index for {India, USA, UK}.
user1509107
source share