在R中基于DataFrame循环调用API批量同步临床试验字段
批量更新临床试验方案字段的R实现
以下是针对需求编写的批量处理代码,实现遍历DataFrame中的PROTOCOL_ID,自动完成获取方案数据→复制字段→提交更新的全流程:
library(jsonlite) library(httr) # 基础配置参数 token <- "12345" base_url <- "https://mywebsite.website.com" endpoint <- "/website-api/rest/protocolManagementDetails/" # 定义单个方案的更新函数 update_protocol_account <- function(protocol_id) { # 构建GET请求地址 get_request_url <- paste0(base_url, endpoint, protocol_id) # 发送GET请求获取方案数据 get_response <- GET(get_request_url, add_headers(authorization = token)) # 检查GET请求是否成功 if (http_status(get_response)$category != "Success") { message(paste("[失败] 无法获取方案ID", protocol_id, ":", http_status(get_response)$message)) return(FALSE) } # 解析返回的JSON数据 protocol_data <- fromJSON(content(get_response, "text")) # 复制internalaccountno到hospitalAccountNo字段 protocol_data$hospitalAccountNo <- protocol_data$internalaccountno # 构建PUT请求地址 put_request_url <- paste0(base_url, endpoint, protocol_id) # 发送PUT请求提交更新 put_response <- PUT(put_request_url, add_headers(authorization = token), body = protocol_data, encode = "json") # 检查PUT请求是否成功 if (http_status(put_response)$category == "Success") { message(paste("[成功] 方案ID", protocol_id, "已更新")) return(TRUE) } else { message(paste("[失败] 方案ID", protocol_id, "更新失败:", http_status(put_response)$message)) return(FALSE) } } # 待处理的方案ID数据集 df <- structure(list(PROTOCOL_ID = c(1, 22, 543, 421, 55, 6), PROTOCOL_NO = c("CTSU-E1234", "BRUOG-j-1234", "tp-P-bob61", "PFIZER-T", "Jimbo", "INCONGRUENCE"), LIBRARY = c("Non-Oncology", "Oncology", "Non-Oncology", "Oncology", "Oncology", "Non-Oncology")), row.names = c(NA, 6L), class = "data.frame") # 执行批量更新 update_results <- lapply(df$PROTOCOL_ID, update_protocol_account) # 输出最终统计结果 total <- length(update_results) success <- sum(unlist(update_results)) message(paste("\n批量更新完成:共处理", total, "个方案,成功", success, "个,失败", total - success, "个"))
关键说明
- 函数封装:将单个方案的操作逻辑打包成函数,让代码更清晰,也便于后续维护和调整。
- 错误处理:在GET和PUT请求后都添加了状态校验,避免单个请求失败导致整个批量任务中断,同时输出明确的失败原因,方便排查问题。
- 批量遍历:使用
lapply遍历DataFrame中的PROTOCOL_ID列,逐个执行更新操作。 - 结果统计:最后输出成功/失败的数量,方便快速核对更新情况。
内容的提问来源于stack exchange,提问作者Joe Crozier
相关产品推荐
相关产品推荐

