R 用列表替换列表中的项

R 用列表替换列表中的项,r,list,R,List,给定一个列表Z就可以了 Z <- list("a"=1, "b"=2, "d"=3) Z[c(1,3)] <- list(list(TRUE,"apple")) Z $`a` $`a`[[1]] [1] TRUE $`a`[[2]] [1] "apple" $b [1] 2 $d $d[[1]] [1] TRUE $d[[2]] [1] "apple" Z这里有一个使用lappy的解决方案。我花了大约10-15分钟在这个问题上摸索,而列表替换只在第一个元素处被截断。问

给定一个列表
Z就可以了

Z <- list("a"=1, "b"=2, "d"=3)

Z[c(1,3)] <- list(list(TRUE,"apple"))

Z
$`a`
$`a`[[1]]
[1] TRUE

$`a`[[2]]
[1] "apple"


$b
[1] 2

$d
$d[[1]]
[1] TRUE

$d[[2]]
[1] "apple"

Z这里有一个使用
lappy
的解决方案。我花了大约10-15分钟在这个问题上摸索,而列表替换只在第一个元素处被截断。问题是我使用了
ifelse
来决定是返回列表还是返回原始元素。切换到正式的
if
else
语句修复了该问题

Z <- list("a"=1, "b"=2, "d"=3)
lst <- list(TRUE, "apple")
indices <- c(1, 3)
output <- lapply(Z, function(x) {
    if (x %in% indices) { lst } else { x }
})

output

$a
$a[[1]]
[1] TRUE

$a[[2]]
[1] "apple"


$b
[1] 2

$d
$d[[1]]
[1] TRUE

$d[[2]]
[1] "apple"
Z
Z <- list("a"=1, "b"=2, "d"=3)
lst <- list(TRUE, "apple")
indices <- c(1, 3)
output <- lapply(Z, function(x) {
    if (x %in% indices) { lst } else { x }
})

output

$a
$a[[1]]
[1] TRUE

$a[[2]]
[1] "apple"


$b
[1] 2

$d
$d[[1]]
[1] TRUE

$d[[2]]
[1] "apple"