Jada Chang
Jada Chang

Reputation: 25

How to replace certain records in a table with another table using "merge"?

I want to replace "O" in table t1 with table t2 using "merge":

t1<-data.frame(x1=c(1,2,3,4,5),x2=c("a","O","O","b","a"))
t2<-data.frame(x1=c(2,3),x2=c("a","b"))
first <- merge(t1["x2"=="O",],t2,by="x1")

The result was supposed to be like this:

t1<-data.frame(x1=c(1,2,3,4,5),x2=c("a","a","b""b","a"))

But I didn't get it.

What's the problem?

Upvotes: 0

Views: 52

Answers (2)

Frank
Frank

Reputation: 66819

I guess merge is messy here (and I wouldn't mess around with this "O" encoding). You can do

m = match(t1$x1, t2$x1)
t1$x2[ !is.na(m) ] <- t2$x2[ m[!is.na(m)] ]

This doesn't extend to merging by more than one column, so I'd recommend data.table:

library(data.table)
setDT(t1)[t2, on="x1", x2 := i.x2]

Upvotes: 2

zacdav
zacdav

Reputation: 4671

This can probably be cleaned up. This is using the dplyr package

first = left_join(t1, t2, by = "x1") %>%
  mutate(x2 = ifelse(x2.x == "O", as.character(x2.y), as.character(x2.x))) %>%
  select(x1, x2)

Upvotes: 0

Related Questions