Home > database >  R Replace a value with a character from another data.table
R Replace a value with a character from another data.table

Time:10-01

Here I met some problems in R about replacement coding.

Here is the original data.table. There are two datatables:

dt1 <- data.table(V1 = c(1,"A"))
dt2 <- data.table("1" = c(4,5,6), "A" = c("c","d","e"))

Now I want to replace values in dt1 with value in dt2 by matching relationship.

The desired output should be:

dt3 <- data.table(V1 = c("4,5,6", "c,d,e"))

That is, I want to replace values in dt1 with all values in the corresponding column in dt2. And this is a simple example, I want to apply it to the whole data.table in R.

I met so big trouble in dealing with this, so please help me.

CodePudding user response:

Here is a way from your input to desired output.

dt1[, V1 := sapply(dt2, paste, collapse = ',')[V1]]


# Test
all.equal(dt1, dt3)
[1] TRUE

PS. Are you sure that storing the values separated by a comma in a string is the best?

CodePudding user response:

We may do

dt1[, V1  := unlist(lapply(V1, function(x) toString(dt2[[x]])))]
dt1
        V1
1: 4, 5, 6
2: c, d, e
  •  Tags:  
  • r
  • Related