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

R语言加载CSV报错:无法合并Reaction.Time列求解决

解决CSV合并时Reaction.Time列类型冲突问题

问题根源

你遇到的报错是因为不同CSV文件中Reaction.Time列的类型不一致:部分文件中该列全为数值,被推断为数值型;而包含"LOADING DELAY"的文件中,该列被推断为字符型。bind_rows无法直接合并不同类型的列,且你后续追加的filter执行在合并之后,根本没机会运行就报错了。

解决方案

需要在读取每个CSV文件时就统一列类型并过滤无效值,再进行合并。以下是具体实现代码:

library(dplyr)

# 指定数据路径,避免重复调用setwd
data_path <- "~/Dropbox/prime/word/data"
age_names <- dir(data_path)

# 定义单个CSV文件的处理函数
process_single_csv <- function(file_name) {
  # 拼接完整文件路径
  full_path <- file.path(data_path, file_name)
  # 读取文件,关闭自动因子转换
  df <- read.csv(full_path, stringsAsFactors = FALSE)
  
  # 处理Reaction.Time列:将非数值转为NA,转成数值型后过滤无效行
  df <- df %>%
    mutate(Reaction.Time = as.numeric(Reaction.Time)) %>%
    filter(!is.na(Reaction.Time))
  
  return(df)
}

# 批量处理所有文件并合并
one <- bind_rows(lapply(age_names, process_single_csv))

代码说明

  1. 统一路径管理:直接用变量存储数据路径,避免重复调用setwd,代码更清晰。
  2. 逐文件预处理:
    • as.numeric(Reaction.Time)会自动将"LOADING DELAY"这类非数值转为NA,同时把整列统一为数值型。
    • filter(!is.na(Reaction.Time))过滤掉包含无效值的行,确保后续合并时列类型完全一致。
  3. 合并数据:经过预处理后,所有数据框的Reaction.Time列都是数值型,bind_rows可以正常合并。

可选进阶处理

如果你想精准只过滤"LOADING DELAY"(避免其他非数值意外被转为NA),可以用case_when明确处理:

process_single_csv <- function(file_name) {
  full_path <- file.path(data_path, file_name)
  df <- read.csv(full_path, stringsAsFactors = FALSE)
  
  df <- df %>%
    mutate(Reaction.Time = case_when(
      Reaction.Time == "LOADING DELAY" ~ NA_character_,
      TRUE ~ Reaction.Time
    )) %>%
    mutate(Reaction.Time = as.numeric(Reaction.Time)) %>%
    filter(!is.na(Reaction.Time))
  
  return(df)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:01:15