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

在Shiny应用中上传CSV转为H2O对象时遇key验证错误求助

解决Shiny+H2O上传CSV时的.key.validate错误

问题重现

在Shiny应用中上传CSV并转为H2O对象时,触发以下错误:

Warning: Error in .key.validate: key must match the regular expression '^[a-zA-Z_][a-zA-Z0-9_.]*$': 0_sid_b018_4

错误原因

  1. H2O对象命名违规:h2o.uploadFile默认用Shiny生成的临时文件路径(如0_sid_b018_4)作为H2O frame的key,但该路径不符合H2O的命名规则——必须以字母/下划线开头,仅允许包含字母、数字、下划线和点。
  2. 代码逻辑错误:原代码试图用read.csv读取H2O对象,而read.csv仅支持本地文件路径,无法处理H2O frame对象。

修复后的完整代码

# 安装并初始化H2O(仅需执行一次)
if ("package:h2o" %in% search()) { detach("package:h2o", unload=TRUE) }
if ("h2o" %in% rownames(installed.packages())) { remove.packages("h2o") }

required_pkgs <- c("methods", "statmod", "stats", "graphics", "RCurl", "jsonlite", "tools", "utils")
for(pkg in required_pkgs) {
  if (!pkg %in% rownames(installed.packages())) { install.packages(pkg) }
}

install.packages("h2o", type = "source", repos = "http://h2o-release.s3.amazonaws.com/h2o/latest_stable_R")
library(h2o)
h2o.init()

# Shiny应用
library(shiny)

# UI定义
ui <- fluidPage(
  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV File",
                multiple = FALSE,
                accept = c("text/csv",
                           "text/comma-separated-values,text/plain",
                           ".csv")),
      tags$hr(),
      checkboxInput("header", "Header", TRUE),
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ","),
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"'),
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),
    mainPanel(
      tableOutput("contents")
    )
  )
)

# Server逻辑
server <- function(input, output) {
  file_info <- reactive({
    req(input$file1)
    
    tryCatch(
      {
        # 生成符合H2O规则的合法key
        raw_name <- tools::file_path_sans_ext(input$file1$name)
        valid_key <- gsub("[^a-zA-Z0-9_.]", "_", raw_name)
        # 确保key以字母/下划线开头
        if (!grepl("^[a-zA-Z_]", valid_key)) {
          valid_key <- paste0("data_", valid_key)
        }
        
        # 先读取为R数据框(适配Shiny输入参数)
        df <- read.csv(input$file1$datapath,
                       header = input$header,
                       sep = input$sep,
                       quote = input$quote)
        # 转为H2O对象并指定合法key
        h2o_data <- as.h2o(df, destination_frame = valid_key)
        
        # 这里可添加H2O对象的后续处理逻辑
        
        # 返回R数据框用于页面展示
        if(input$disp == "head") {
          head(df)
        } else {
          df
        }
      },
      error = function(e) {
        stop(safeError(e))
      }
    )
  })
  
  output$contents <- renderTable({
    file_info()
  })
}

# 启动应用
shinyApp(ui, server)

关键修改点

  • 生成合法H2O key:提取上传文件名并清洗非法字符,确保符合H2O的命名规则
  • 修正读取逻辑:先通过read.csv读取本地临时文件为R数据框,再用as.h2o转为H2O对象,同时显式指定合法的destination_frame参数
  • 移除重复初始化:删除重复的h2o.init()调用,避免资源浪费

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:05:13