为什么我不能 purrr:: 在没有匿名函数的情况下映射这个列表(sapply 有效)
Why can't I purrr:: map this list without anonymous function (sapply works)
我最近尝试在某些 sapply
运行良好的代码中使用 map_dbl
,但偶然发现了下面的不一致之处。怎么了?
library(nlme)
fm1 = nlsList(uptake ~ SSasympOff(conc, Asym, lrc, c0),
data = CO2, start = c(Asym = 30, lrc = -4.5, c0 = 52))
# Ok
deviance = sapply(fm1, function(x) deviance(x))
deviance = sapply(fm1, deviance)
deviance = purrr::map_dbl(fm1, function(x) deviance(x))
# fails
deviance = purrr::map_dbl(fm1, deviance)
# Error: Result 1 is not a length 1 atomic vector
str(deviance(fm1[[1]]))
# num 11.1
purrr
不会将 deviance
解释为函数,因为您有一个函数 deviance
和一个名为 deviance
[=24= 的变量(在全局环境中) ]
purrr
在内部对第二个参数使用 as_function
。所以在你的情况下:
deviance = sapply(fm1, deviance)
class(deviance) # "numeric"
在这个意义上 deviance
被解释为数值向量。来自 ?map
If character or integer vector, e.g. "y", it is converted to an
extractor function, function(x) x[["y"]]. To index deeply into a
nested list, use multiple values; c("x", "y") is equivalent to
z[["x"]][["y"]]. You can also set .null to set a default to use
instead of NULL for absent components.
以下作品:
rm(deviance)
my_deviance = purrr::map_dbl(fm1, deviance)
一样:
purrr::map_dbl(fm1, ~deviance(.x))
和:
deviance = sapply(fm1, deviance)
map_dbl(fm1, stats::deviance)
和(@Axeman 在评论中提到)
purrr::map_dbl(fm1, match.fun(deviance))
我最近尝试在某些 sapply
运行良好的代码中使用 map_dbl
,但偶然发现了下面的不一致之处。怎么了?
library(nlme)
fm1 = nlsList(uptake ~ SSasympOff(conc, Asym, lrc, c0),
data = CO2, start = c(Asym = 30, lrc = -4.5, c0 = 52))
# Ok
deviance = sapply(fm1, function(x) deviance(x))
deviance = sapply(fm1, deviance)
deviance = purrr::map_dbl(fm1, function(x) deviance(x))
# fails
deviance = purrr::map_dbl(fm1, deviance)
# Error: Result 1 is not a length 1 atomic vector
str(deviance(fm1[[1]]))
# num 11.1
purrr
不会将 deviance
解释为函数,因为您有一个函数 deviance
和一个名为 deviance
[=24= 的变量(在全局环境中) ]
purrr
在内部对第二个参数使用 as_function
。所以在你的情况下:
deviance = sapply(fm1, deviance)
class(deviance) # "numeric"
在这个意义上 deviance
被解释为数值向量。来自 ?map
If character or integer vector, e.g. "y", it is converted to an extractor function, function(x) x[["y"]]. To index deeply into a nested list, use multiple values; c("x", "y") is equivalent to z[["x"]][["y"]]. You can also set .null to set a default to use instead of NULL for absent components.
以下作品:
rm(deviance)
my_deviance = purrr::map_dbl(fm1, deviance)
一样:
purrr::map_dbl(fm1, ~deviance(.x))
和:
deviance = sapply(fm1, deviance)
map_dbl(fm1, stats::deviance)
和(@Axeman 在评论中提到)
purrr::map_dbl(fm1, match.fun(deviance))