Replace value in R data.frame -


i replace/update values in r data.frame, please see example below:

original data.frame originaldf contains cars, price , size columns:

    cars <- c("ford", "gm")     price <- c(10,  20)     size <- c(1,2)       originaldf <- data.frame(cars=cars, price=cbind(price), size=cbind(size))      originaldf:     cars price size   1 ford    10    1   2   gm    20    2 

then want replace/update values in originaldf new values (smaller) newdf, assume newdf single record of sale:

cars <- "ford" price  <- 15 color  <- "white" newdf <- data.frame(cars=cars, price=cbind(price),color=cbind(color))  newdf: cars price color 1 ford    15 white 

so final result.

modifieddf:   cars price 1 ford    15 2   gm    20 

please note newdf has additional values not included in originaldf , not needed. @ same time originaldf may have columns may not presented in newdf , therefore cannot updated.

find rows match. change values.

rows <- originaldf$cars %in% newdf$cars originaldf[rows, -1] <- newdf[, -1] 

note above assumes same column order originaldf , newdf. if not guaranteed, replace -1 in [, ] proper column names


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -