使用mutate生成total_policies变量后提示‘object not found’的解决
解决mutate后变量找不到的问题
嘿,我知道你卡在哪了!你写的这段代码:
mhomes %>% mutate(total_policies = rowSums(select(., starts_with("num"))))
确实正确计算出了total_policies这个新变量,但dplyr的管道操作默认只是返回修改后的临时数据框,并没有把结果保存到原有的mhomes变量里。所以当你后续直接调用total_policies或者用summary(total_policies)时,R既找不到这个单独的变量,原数据框mhomes里也没有新增这个列,自然会报错说找不到对象。
下面给你几个解决办法:
直接更新原数据框:把管道操作的结果重新赋值回
mhomes,这样原数据框就会包含新变量了:mhomes <- mhomes %>% mutate(total_policies = rowSums(select(., starts_with("num"))))之后你就可以正常使用
summary(mhomes$total_policies),或者在绘图时引用mhomes$total_policies了。保存到新数据框(不修改原数据):如果不想改动原始数据,可以把结果存到一个新变量里:
mhomes_with_total <- mhomes %>% mutate(total_policies = rowSums(select(., starts_with("num"))))后续用
summary(mhomes_with_total$total_policies)或者基于这个新数据框进行绘图操作。简化代码(推荐):在较新的dplyr版本里,更推荐用
across()代替select()来指定列,代码更简洁规范:mhomes <- mhomes %>% mutate(total_policies = rowSums(across(starts_with("num"))))临时链式操作:如果只是想一次性查看汇总或绘图,不用单独保存变量,可以直接在管道里链式完成:
# 直接查看包含新变量的汇总结果 mhomes %>% mutate(total_policies = rowSums(across(starts_with("num")))) %>% summary() # 直接基于新变量绘图 mhomes %>% mutate(total_policies = rowSums(across(starts_with("num")))) %>% ggplot(aes(x = total_policies)) + geom_histogram()
内容的提问来源于stack exchange,提问作者Florence V
相关产品推荐
相关产品推荐

