R语言数据处理:新增Top5Countries列标记指定国家
问题解决方法
错误原因
你代码里的逻辑判断写法有误:|(逻辑或)的两侧必须是逻辑值,但你直接把字符串(比如"USA")放在|后面,R无法将字符串转换为逻辑类型进行运算,所以抛出了类型不匹配的错误。
正确实现方式
方法1:使用%in%(推荐)
%in%可以直接判断列值是否在指定的向量中,写法更简洁高效:
# 定义Top5国家列表 top5_countries <- c("USA", "UK", "Netherlands", "Germany", "Singapore") # 新增Top5Countries列 cleaneddata$Top5Countries <- if_else(cleaneddata$Country_Region %in% top5_countries, 1, 0)
方法2:修正逻辑或的写法
如果一定要用多个==加|,需要保证每个条件都是列与单个字符串的比较:
cleaneddata$Top5Countries <- if_else( cleaneddata$Country_Region == "USA" | cleaneddata$Country_Region == "UK" | cleaneddata$Country_Region == "Netherlands" | cleaneddata$Country_Region == "Germany" | cleaneddata$Country_Region == "Singapore", 1, 0 )
注意:你原代码里列名写的是countryRegion,但问题描述里是Country_Region,要确保列名和数据里的一致,避免因大小写或拼写错误导致的问题。
内容的提问来源于stack exchange,提问作者Ali Abdullah Khan
相关产品推荐
相关产品推荐

