Helen Neely Helen Neely - 1 month ago 17
R Question

How do I update data frame fields in R?

I'm looking to update fields in one data table with information from another data table like this:

dt1$name <- dt2$name where dt1$id = dt2$id

In SQL pseudo code : update dt1 set name = dt2.name where dt1.id = dt2.id


As you can see I'm very new to R so every little helps.

Update
I think it was my fault - what I really want is to update an telephone number if the usernames from both dataframes match.

So how can I compare names and update a field if both names match?
Please help :)

dt1$phone<- dt2$phone where dt1$name = dt2$name

Answer

Joran's answer assumes dt1 and dt2 can be matched by position.

If it's not the case, you may need to merge() first:

dt1 <- data.frame(id = c(1, 2, 3), name = c("a", "b", "c"), stringsAsFactors = FALSE)
dt2 <- data.frame(id = c(7, 3), name = c("f", "g"), stringsAsFactors = FALSE)
dt1 <- merge(dt1, dt2, by = "id", all.x = TRUE)
dt1$name <- ifelse( ! is.na(dt1$name.y), dt1$name.y, dt1$name.x)
dt1

(Edit per your update:

dt1 <- data.frame(id = c(1, 2, 3), name = c("a", "b", "c"), phone = c("123-123", "456-456", NA), stringsAsFactors = FALSE)
dt2 <- data.frame(name = c("f", "g", "a"), phone = c(NA, "000-000", "789-789"), stringsAsFactors = FALSE)
dt1 <- merge(dt1, dt2, by = "name", all.x = TRUE)
dt1$new_phone <- ifelse( ! is.na(dt1$phone.y), dt1$phone.y, dt1$phone.x)