使用mutate()和recode修改经度值时遭遇'unexpected ='错误求助
问题解决:修正mutate+recode的语法错误
你的代码报错核心有两个语法问题:
- recode的目标列不能加引号:你把列名
"Camelot GPS Longitude"用引号括起来,R会把它识别成普通字符串,而非要操作的列。带空格的列名需要用反引号()包裹,或者用.data$`前缀引用。 - 数值匹配规则的语法错误:recode里用等号定义替换规则时,左边的数值不能直接写(比如
93.2142 = ...),语法不允许,必须用反引号把匹配的数值包起来。
修正后的recode写法:
site <- site %>% mutate(`Camelot GPS Longitude` = recode(`Camelot GPS Longitude`, `93.2142` = -93.2142, `93.18124` = -93.18124))
更稳妥的替代方案:用case_when
如果觉得recode的语法容易踩坑,推荐用case_when,逻辑更直观,也不用处理反引号的问题:
site <- site %>% mutate(`Camelot GPS Longitude` = case_when( `Camelot GPS Longitude` == 93.2142 ~ -93.2142, `Camelot GPS Longitude` == 93.18124 ~ -93.18124, TRUE ~ `Camelot GPS Longitude` # 保留其他未匹配的原始值 ))
额外提醒:如果你的数据是浮点型,要注意精度问题——比如实际存储的数值可能是93.21420001这类近似值,直接用==匹配会失效,这种情况可以用near()函数替代,写法为near(Camelot GPS Longitude, 93.2142)。
内容的提问来源于stack exchange,提问作者diana phillips
相关产品推荐
相关产品推荐

