使用Plumber构建R API时rnorm()参数无效报错求助
解决Plumber API中rnorm参数无效的问题
问题根源
Plumber从HTTP请求接收的参数默认是字符类型,而rnorm()函数的mean参数要求传入数值类型。直接将字符型的mean传入rnorm()会触发类型不匹配,导致"invalid arguments"错误。
对比你提供的正常运行的iris示例:示例中的spec参数是字符串类型,与iris$Species(字符/因子类型)匹配,不需要类型转换,因此可以正常执行。
修复方案
以下两种方法都能解决问题:
方法1:手动转换参数类型并添加校验
在函数内部将字符型参数转为数值型,同时增加校验避免无效输入:
#* Plot out data from a random normal distribution #* @param mean The mean of the normal distribution #* @get /plot #* @serializer png function(mean) { # 将请求参数转为数值型 mean_val <- as.numeric(mean) # 校验转换结果,若为NA则抛出明确错误 if (is.na(mean_val)) { stop("Parameter 'mean' must be a valid numeric value") } hist(rnorm(n = 1000, mean = mean_val, sd = 1)) }
方法2:使用Plumber的参数类型标注
通过@param mean:numeric指定参数类型,Plumber会自动将请求中的参数转为数值型,转换失败时返回标准化错误:
#* Plot out data from a random normal distribution #* @param mean:numeric The mean of the normal distribution #* @get /plot #* @serializer png function(mean) { hist(rnorm(n = 1000, mean = mean, sd = 1)) }
验证方式
调用接口时传入数值型参数(如/plot?mean=2),即可正常生成直方图。
内容的提问来源于stack exchange,提问作者MCP_infiltrator
相关产品推荐
相关产品推荐

