R:ifelse函数返回向量位置而不是值(字符串) [英] R: ifelse function returns vector position instead of value (string)

查看:465
本文介绍了R:ifelse函数返回向量位置而不是值(字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于ifelse函数,我有一个非常奇怪的问题:它不会返回一个因子(如我所愿),而是类似于因子的位置。

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.

..是一个新的专栏df包含国家名称,如果该国家属于前12个最常见的国家(在答案栏中)。否则它应该包含其他

..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"

...是


  • 使用as.data.frame(摘要等等)创建一个包含最频繁国家/地区名称的列表##此作品

  • 函数的TRUE部分将df $ col值与此列表匹配使用%in%##这也适用

  • 如果TRUE应为因子(国家/地区名称),则返回值那个

... R返回一些非常奇怪的东西:它返回前10个国家的因子级别(1到181之间)的位置,以及其他国家的其他(这是正常的)。这一行返回错误的值:

... 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。这是这个,因为它有些不同,可能需要一个单独的问题。

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

推荐答案

字段 answer 是因子,因此您的函数返回数字(因子级别)。

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

您需要什么do是:

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

然后才有效。

这篇关于R:ifelse函数返回向量位置而不是值(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆