如何一键将R函数参数赋值到环境以辅助调试?
在R中快速将函数参数赋值到当前环境的调试技巧
当自定义R函数需要逐行调试时,手动将函数的传入参数和默认参数赋值到当前环境会很繁琐。比如有如下函数:
myfun <- function(x, y, z = 3, message = c("testing","with","y=")) { cat(paste(message, collapse = " "), y, "\n") if(x<2) x <- as.character(x) res <- x+y-z return(res) } # 正常运行 myfun(3,1) # 运行报错 myfun(1,3)
调试时需要手动赋值所有参数:
x = 1 y = 3 z = 3 message = c("testing","with","y=")
可以通过以下方法实现一行代码将参数批量导入当前环境:
方法1:针对特定调用快速导入参数
直接运行以下代码(替换myfun(1,3)为你需要调试的函数调用):
list2env(modifyList(formals(myfun), as.list(match.call(myfun, myfun(1,3)))[-1]), .GlobalEnv)
运行后,当前环境会自动生成x=1、y=3、z=3、message=c("testing","with","y=")这些变量,直接逐行运行函数代码即可调试。
方法2:封装成工具函数复用
如果需要多次使用,可以封装成一个通用函数:
load_fun_args <- function(target_call) { # 获取函数对象 fun_obj <- eval(target_call[[1]]) # 获取调用传入的参数 call_args <- as.list(match.call(fun_obj, target_call))[-1] # 合并默认参数与传入参数 full_args <- modifyList(formals(fun_obj), call_args) # 导入到当前环境 list2env(full_args, envir = .GlobalEnv) } # 使用示例:导入myfun(1,3)的所有参数 load_fun_args(myfun(1,3))
补充说明
match.call()用于捕获函数调用时的参数输入formals()获取函数的默认参数列表modifyList()将传入参数覆盖到默认参数列表,得到完整的参数集合list2env()将参数列表中的键值对转化为当前环境的变量
内容的提问来源于stack exchange,提问作者Rosalie Bruel
相关产品推荐
相关产品推荐

