Replace list values ​​with others in R

a, b and c are a list.

a<-list(c(6,5,7),c(1,2),c(1,3,4))
b<-list(c(1,2,3),c(4,5),c(6,7,8))
c<-list(1,2,2)

I want to replace "a" with "b" in place of "c" to create a new list.

Expected Result:

[[1]]
[1] 1 5 7

[[2]]
[1] 1 5

[[3]]
[1] 1 7 4

Thank you for your help!

+4
source share
2 answers

It looks like you are looking Mapto iterate through all lists at once.

Map(function(a,b,c) {a[c]<-b[c]; a},a,b,c)
# [[1]]
# [1] 1 5 7
#
# [[2]]
# [1] 1 5
#
# [[3]]
# [1] 1 7 4
+8
source

For R-newbies who find that finding syntax is Mapawesome:

for(i in seq(c)){
  a[[i]][unlist(c[i])] <- b[[i]][unlist(c[i])]
}
a

# [[1]]
# [1] 1 5 7
#
# [[2]]
# [1] 1 5
#
# [[3]]
# [1] 1 7 4
0
source

Source: https://habr.com/ru/post/1627901/


All Articles