Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

r - Change values in a list of vectors according to a key

I have a list of vectors as following:-

a <- list(c("10002", "10003", "10004"), c("10001", "10005"),
          c("10001", "10004"), c("10003", "10005"), c("10002", "10003"))

And I have a data.frame which is as following:-

b <- data.frame(col1=c(1, 2, 3, 4, 5),
                col2=c("10001", "10002", "10003", "10004", "10005"))

So basically I want to replace the character values of in list a by the corresponding numeric values in col1 of b . So that my list will become:-

c <- list(c(2, 3, 4), c(1, 5), c(1, 4), c(3, 5), c(2, 3))

Thanks in advance.

question from:https://stackoverflow.com/questions/65858129/change-values-in-a-list-of-vectors-according-to-a-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can unlist a values, match with col2 and get the corresponding col1 values. Finally we use relist to maintain the same structure as a.

relist(b$col1[match(unlist(a), b$col2)], a)

#[[1]]
#[1] 2 3 4

#[[2]]
#[1] 1 5

#[[3]]
#[1] 1 4

#[[4]]
#[1] 3 5

#[[5]]
#[1] 2 3

You can also use lapply with match.

lapply(a, function(x) b$col1[match(x, b$col2)])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...