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

R语言导入CSV时解决列间小数分隔符不一致问题

解决R语言中不同列小数分隔符统一问题

针对你遇到的两列小数分隔符不一致的情况,可以分两种场景处理:

场景1:导入数据时直接处理

修改read_delim的列类型设置,先将temperature和precipitation读为字符型,再分别转换为数值型:

weather_bergen <- read_delim(file = "bergen_weather.csv",
                             delim = ";",
                             col_names = c("name", "station", "date", "temperature", "precipitation"),
                             skip = 1, 
                             col_types = cols(
                               date = col_date("%m.%Y"),
                               temperature = col_character(),
                               precipitation = col_character()
                             )) |> 
  drop_na(date) |>
  mutate(
    # temperature本身是点分隔,直接转数值
    temperature = as.numeric(temperature),
    # precipitation把逗号替换成点后转数值
    precipitation = as.numeric(str_replace(precipitation, ",", "."))
  )

注意:需要先加载dplyr和stringr包(或直接加载tidyverse),因为用到了mutate和str_replace函数

场景2:已导入数据后的修改

如果已经有了导入好的weather_bergen对象,直接运行以下代码修改precipitation列:

library(dplyr)
library(stringr)

weather_bergen <- weather_bergen |>
  mutate(
    precipitation = as.numeric(str_replace(precipitation, ",", "."))
  )

如果temperature列因导入设置被错误解析为字符型,可补充temperature = as.numeric(temperature)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:45:49