[英]Replacing values within list elements
我有以下兩個列表:
list1 <- list(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1), c(1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0), c(0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1))
list2 <- list(c(9, 10, 11, 12, 13), c(5, 6, 7, 8, 9, 10, 11, 12, 13), c(1, 2, 3, 8, 9, 10, 11, 12, 13))
list2
代表list1
中我想轉換為0
。 換句話說,我希望list1
的第一個元素中的第9個,第10個,第11個,第12個和第13個值為0
; 我希望list1
的第二個元素中的第5到第13個值為0
; 等等。結果列表應為以下內容:
list3 <- list(c(1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0), c(1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0), c(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0))
我怎樣才能做到這一點? 謝謝!
我們可以使用purrr::map2
做到這tidyverse
:
list1 <- list(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1), c(1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0), c(0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1))
list2 <- list(c(9, 10, 11, 12, 13), c(5, 6, 7, 8, 9, 10, 11, 12, 13), c(1, 2, 3, 8, 9, 10, 11, 12, 13))
library(purrr)
map2(
.x = list1,
.y = list2,
.f = function(list, indexes){
list[indexes] <- 0
list
}
)
#> [[1]]
#> [1] 1 1 1 1 1 1 1 1 0 0 0 0 0
#>
#> [[2]]
#> [1] 1 1 1 1 0 0 0 0 0 0 0 0 0
#>
#> [[3]]
#> [1] 0 0 0 1 1 1 1 0 0 0 0 0 0
由reprex軟件包 (v0.2.0)於2018-10-22創建。
這是使用for
循環的一種快速而骯臟的方法:
for(i in 1:length(list1)){
list1[[i]][list2[[i]]]<-0
}
我確信有人可以使用lapply或purrr中的函數對此進行改進。
在基數R中使用一個簡單的循環,
for(i in 1:length(list1)) {
list1[[i]][list2[[i]]] <- 0
}
> list1
[[1]]
[1] 1 1 1 1 1 1 1 1 0 0 0 0 0
[[2]]
[1] 1 1 1 1 0 0 0 0 0 0 0 0 0
[[3]]
[1] 0 0 0 1 1 1 1 0 0 0 0 0 0
您還可以使用如下所示的mapply()
執行此操作,其中SIMPLIFY=F
強制函數以列表形式返回。
funfun <- function(x, y, recode=0) {
x[y] <- recode
return(x)
}
mapply(list1, list2, FUN=funfun, SIMPLIFY=F)
[[1]]
[1] 1 1 1 1 1 1 1 1 0 0 0 0 0
[[2]]
[1] 1 1 1 1 0 0 0 0 0 0 0 0 0
[[3]]
[1] 0 0 0 1 1 1 1 0 0 0 0 0 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.