-2

first dataframe like this, with quite few columns:

name C1 C2 C3 ....
a 2 3 5 .....
b 4 5 6 ....
c 6 2 3 ....

second dataframe like this:

id C_name
2 apple
3 banana
4 orange
5 grape
6 kiwi

I would like to replace the numbers in the first dataframe with the names in second dataframe, it should look like this

name C1 C2 C3 ....
a apple banana grape .....
b orange grape kiwi ....
c kiwi apple banana ....

thank you

1
  • What did you try to do? Commented Feb 2, 2021 at 15:22

1 Answer 1

2
dat2vec <- setNames(dat2$C_name, dat2$id)
dat1[2:4] <- lapply(dat1[2:4], function(z) dat2vec[as.character(z)])
dat1
#   name     C1     C2     C3  ....
# 1    a  apple banana  grape .....
# 2    b orange  grape   kiwi  ....
# 3    c   kiwi  apple banana  ....

or

dat1[2:4] <- lapply(dat1[2:4], function(z) {
  ind <- match(z, dat2$id)
  replace(z, !is.na(ind), dat2$C_name[ind])
})

Data

dat1 <- structure(list(name = c("a", "b", "c"), C1 = c("apple", "orange", "kiwi"), C2 = c("banana", "grape", "apple"), C3 = c("grape", "kiwi", "banana"), .... = c(".....", "....", "....")), row.names = c(NA, -3L), class = "data.frame")
dat2 <- structure(list(id = 2:6, C_name = c("apple", "banana", "orange", "grape", "kiwi")), class = "data.frame", row.names = c(NA, -5L))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.