You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R编程:将带$符号的字符型price列转换为数值型

问题原因

  • 你直接对带$符号的字符列调用as.numeric(),R无法识别非数字字符,会直接将值转换为NA,这是出现全NA的核心原因
  • 其次你的代码存在语法错误:mutate_at的调用方式不符合dplyr管道规范,操作列需要用vars()包裹,且不能直接在管道后单独赋值生成新列

正确实现代码

如果需要直接覆盖原有price列:

library(tidyverse)
library(janitor)

rental_df <- rental_df %>%
  mutate(location = sub(".*in ", "", location)) %>%
  # 先移除价格中的$符号和千位分隔符逗号,再转换为数值型
  mutate(price = as.numeric(str_remove_all(price, "\\$|,"))) %>%
  clean_names()

如果需要保留原price列,生成新的数值列price_1:

library(tidyverse)
library(janitor)

rental_df <- rental_df %>%
  mutate(location = sub(".*in ", "", location)) %>%
  mutate(price_1 = as.numeric(str_remove_all(price, "\\$|,"))) %>%
  clean_names()

内容的提问来源于stack exchange,提问作者Hayley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:27:04