0

I have two data frames in R and I need to update the values in one data frame with the value in another data frame. I could easily do this in SQL using UPDATEbut for whatever reason the SQLite in R doesn't seem to process the same way.

Sample example:

DF1 

col A   

xyz      
123

DF2 

col A   col B

xyz     abc
123     456

I would like to replace col A in DF1 with the values in col B from DF2 based on the fact that col A from DF1 are equal to values in col A from DF2. Given I am pretty new to R. in SQL this would be a simple UPDATE statement but I can't get the syntax to work in sqldf

this seems to do what I was needing - I just wasn't familiar with the syntax:

DF1$colA <- DF2[match(DF1$colA,DF2$colB),2]
XCCH004
  • 321
  • 1
  • 11

1 Answers1

2

You can use an ifelse to check equality and replace with Col_B from df2 otherwise leave the value of Col_A in df1 as-is. Here is how:

df1$Col_A=ifelse(as.character(df1$Col_A) == as.character(df2$Col_A), as.character(df2$Col_B), as.character(df1$Col_A)
# df1
# Col_A
# 1   abc
# 2   456
# 3   567

Data

df1 <- data.frame(Col_A=c("xyz", "123", "567"))                                                                                                                                                                                                       
df2 <- data.frame(Col_A = c("xyz", "123"), 
                  Col_B = c("abc", "456"))

Hope this helps.

deepseefan
  • 3,701
  • 3
  • 18
  • 31