关于ifelse函数,我有一个非常奇怪的问题:它不会返回一个因子(我想要的),而是像因子的位置一样.
我使用的数据集可以在这里下载.
..在df中创建一个新列,其中包含国家/地区的名称,如果该国家/地区属于前12个最常见的国家/地区(在"答案"列中).否则它应该包含"其他"
......是
... R返回一些非常奇怪的东西:它返回前10个国家的因子级别(1到181之间)的位置,以及其他国家的"其他"(这是正常的).这一行返回错误的值:
aDDs$answer, ## then it should be named as aDDs$answer **THIS IS THE PROBLEM**
Run Code Online (Sandbox Code Playgroud)
## 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)
Run Code Online (Sandbox Code Playgroud)
PS.这是对这个问题的后续问题,因为它有些不同,可能需要一个单独的问题.
Zby*_*nek 17
该字段answer是因子,因此您的函数返回数字(因子级别).
你需要做的是:
aDDs$answer <- as.character(aDDs$answer)
Run Code Online (Sandbox Code Playgroud)
然后它的工作原理.