Shawn Brar
Shawn Brar

Reputation: 1420

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.

Upvotes: 0

Views: 39

Answers (2)

Eyayaw
Eyayaw

Reputation: 1081

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

Alternative: since I found out, after posting my answer, that my answer is identical to Ronak's

lapply(a, function(x) ifelse(x %in% b$col2, b$col1, NA))

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

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)])

Upvotes: 2

Related Questions