在函数内的 get() 上使用 purrr 的 map() 函数,导致找不到对象
Use purrr's map() function on get() within function, results in object not found
使用以下代码时:
get_objects <- function() {
x1 <- 123
x2 <- 23535
x_objects <- ls(pattern = 'x')
print(x_objects)
x_objects_list <- purrr::map(x_objects, get)
return(x_objects_list)
}
f <- get_objects()
我收到以下错误:
Error in .f(.x[[i]], ...) : object 'x1' not found
我怀疑它与作用域或环境有关,因为当对象是全局定义的而不是在函数中时,我可以通过评估来使用代码
x_objects_list <- purrr::map(x_objects, get)
直接在控制台中。原因是我想要一个具有特定名称的数据帧列表,以便我可以对它们迭代执行操作。
不确定您要做什么,但由于您没有分享更大的范围,这应该可以解决您当前的问题:
get_objects <- function() {
x1 <- 123
x2 <- 23535
x_objects <- ls(pattern = 'x')
x_objects_list <- purrr::map(x_objects, get, envir = sys.frame(sys.parent(0)))
return(x_objects_list)
}
f <- get_objects()
使用以下代码时:
get_objects <- function() {
x1 <- 123
x2 <- 23535
x_objects <- ls(pattern = 'x')
print(x_objects)
x_objects_list <- purrr::map(x_objects, get)
return(x_objects_list)
}
f <- get_objects()
我收到以下错误:
Error in .f(.x[[i]], ...) : object 'x1' not found
我怀疑它与作用域或环境有关,因为当对象是全局定义的而不是在函数中时,我可以通过评估来使用代码
x_objects_list <- purrr::map(x_objects, get)
直接在控制台中。原因是我想要一个具有特定名称的数据帧列表,以便我可以对它们迭代执行操作。
不确定您要做什么,但由于您没有分享更大的范围,这应该可以解决您当前的问题:
get_objects <- function() {
x1 <- 123
x2 <- 23535
x_objects <- ls(pattern = 'x')
x_objects_list <- purrr::map(x_objects, get, envir = sys.frame(sys.parent(0)))
return(x_objects_list)
}
f <- get_objects()