Tanya Valkanova
Tanya Valkanova

Reputation: 209

Geting new data into old data frame in R

I have an OD problem with getting new data data frame into old one.

old<-data.frame(O=c("I","A","B","D","R","F","A"),D=c("I","F","C","B","D","G","B"),F3=c(1:7))
new<-data.frame(O=c("F","D","R","F","A"),D=c("G","B","D","G","F"),F3=c(11,0,13,14,16))
old$OD<-paste(old$O, old$D, sep=" ")
new$OD<-paste(new$O, new$D, sep=" ")

The old data:

> old
  O D F3  OD
1 I I  1 I I
2 A F  2 A F
3 B C  3 B C
4 D B  4 D B
5 R D  5 R D
6 F G  6 F G
7 A B  7 A B

and the new one:

> new
  O D F3  OD
1 F G 11 F G
2 D B  0 D B
3 R D 13 R D
4 F G 14 F G
5 A F 16 A F

I want to substitude the old F3 value with the new one based on common OD.

I have tried:

Old_new1<-merge(old,new, by = "OD")


Old_new2<- ifelse(old$OD %in%  new$OD,new$F3,old$F3 )
Old_new2<-data.frame(old,Old_new2)

I wann to get:

> old_new
      O D F3  OD F3_new
    1 I I  1 I I  1
    2 A F  2 A F 16
    3 B C  3 B C  3
    4 D B  4 D B  0
    5 R D  5 R D 13
    6 F G  6 F G 14
    7 A B  7 A B  7

I want to be abel to compere it first befor substituting.

Thanks!

Upvotes: 2

Views: 44

Answers (1)

akrun
akrun

Reputation: 887048

We could use a data.table join on the 'OD' and assign (:=) the 'F3' column values in 'new' (i.F3) to the 'F3' column in 'old'

library(data.table)
new$F3 <- as.integer(new$F3) # as the class for old 'F3' is `integer`
setDT(old)[new, F3 := i.F3, on = .(OD)]
old
#   O D F3  OD
#1: I I  1 I I
#2: A F 16 A F
#3: B C  3 B C
#4: D B  0 D B
#5: R D 13 R D
#6: F G 14 F G
#7: A B  7 A B

Upvotes: 1

Related Questions