I\'m trying to figure out how to use merge()
to update a database.
Here is an example. Take for example the data frame foo
I would also like to present an sql-solution using library sqldf and the R integrated sqlite-database. I like the simplicity, accuratness and power of sql.
Accurateness: since I can exactly define which object=rows I want to change without considering the order of a data.frame (foo.id = bar.id
).
Power: in WHERE after SET and WHERE (third row) I can define all conditions I want to consider to update.
Simplicity: the syntax is more readable than using index in vectors, matrix or dataframes.
library(sqldf)
# I changed index to id since index does not work.
# Obviously index is a key word in sqlite.
(foo <- data.frame(id=c('a', 'b', 'c', 'd'), value=c(100, 101, NA, NA)))
(bar <- data.frame(id=c('c', 'd'), value=c(200, 201)))
sqldf(c(paste("UPDATE foo"
," SET value = (SELECT bar.value FROM bar WHERE foo.id = bar.id)"
," WHERE value IS NULL"
)
, " SELECT * FROM main.foo"
)
)
Which gives
id value
1 a 100
2 b 101
3 c 200
4 d 201
Similar issues:
r equivalent of sql update?
R sqlite: update with two tables