R 用[[<-
有人能解释一下为什么使用purrr会出现错误:R 用[[<-,r,purrr,R,Purrr,有人能解释一下为什么使用purrr会出现错误: map(list(list(a=1, b=2, c=3), list(a=1, b=2, c=3)), `[[<-`, "b", 1) 图(列表)(列表(A=1,B=2,C=3),列表(A=1,B=2,C=3)),[[ < P>问题在于 PURR::ASSMAPPER(): > > (或)>代码>在引擎盖下调用。考虑不同: x <- list( a=1, b=2, c=3 ) `[[<-`( x, "b", 1 )
map(list(list(a=1, b=2, c=3), list(a=1, b=2, c=3)), `[[<-`, "b", 1)
图(列表)(列表(A=1,B=2,C=3),列表(A=1,B=2,C=3)),[[ < P>问题在于<代码> PURR::ASSMAPPER():<代码> > > <代码>(或)>代码>在引擎盖下调用。考虑不同:
x <- list( a=1, b=2, c=3 )
`[[<-`( x, "b", 1 ) # This is what lapply() calls
# x is unchanged, returns modified list
purrr::as_mapper(`[[<-`)( x, "b", 1 ) # This is what map() calls
# x is modified in-place, returns value 1
与您的lappy()
示例相对应的purrr
等价物应该如下所示:
r1 <- lapply(y, `[[<-`, "b", 1)
r2 <- purrr::map(y, purrr::modify_at, "b", ~1)
r3 <- purrr::map(y, ~`[[<-`(.x, "b", 1))
identical( r1, r2 ) # TRUE
identical( r1, r3 ) # TRUE
r1
y <- list(list(a=1, b=2, c=3), list(a=1, b=2, c=3))
purrr::map( y, ~purrr::as_mapper(`[[<-`)(.x, "b", 1) )
# [[1]]
# [1] 1
# [[2]]
# [1] 1
purrr::map( y, purrr::as_mapper(`[[<-`), "b", 1 )
# Error in list(a = 1, b = 2, c = 3)[["b"]] <- 1 :
# target of assignment expands to non-language object
r1 <- lapply(y, `[[<-`, "b", 1)
r2 <- purrr::map(y, purrr::modify_at, "b", ~1)
r3 <- purrr::map(y, ~`[[<-`(.x, "b", 1))
identical( r1, r2 ) # TRUE
identical( r1, r3 ) # TRUE