merge - Have nomatch return value as-is using match function in R -



merge - Have nomatch return value as-is using match function in R -

i have much larger existing dataframe. smaller illustration replace of variables (replace state (df1)) newstate (df2) according column "first." issue values returned na since of names matched in new dataframe (df2).

existing dataframe:

state = c("ca","wa","or","az") first = c("jim","mick","paul","ron") df1 <- data.frame(first, state) first state 1 jim ca 2 mick wa 3 paul or 4 ron az

new dataframe match existing dataframe

state = c("ca","wa") newstate = c("tx", "la") first =c("jim","mick") df2 <- data.frame(first, state, newstate) first state newstate 1 jim ca tx 2 mick wa la

tried utilize match returns na "state" matching "first" variable df2 not found in original dataframe.

df1$state <- df2$newstate[match(df1$first, df2$first)] first state 1 jim tx 2 mick la 3 paul <na> 4 ron <na>

is there way ignore nomatch or have nomatch homecoming existing variable as-is? illustration of desired result: jim/mick's states updated while paul , ron's state not change.

first state 1 jim tx 2 mick la 3 paul or 4 ron az

is want; btw unless want work factors, utilize stringsasfactors = false in data.frame call. notice utilize of nomatch = 0 in match call.

> state = c("ca","wa","or","az") > first = c("jim","mick","paul","ron") > df1 <- data.frame(first, state, stringsasfactors = false) > state = c("ca","wa") > newstate = c("tx", "la") > first =c("jim","mick") > df2 <- data.frame(first, state, newstate, stringsasfactors = false) > df1 first state 1 jim ca 2 mick wa 3 paul or 4 ron az > df2 first state newstate 1 jim ca tx 2 mick wa la > > # create index matches > indx <- match(df1$first, df2$first, nomatch = 0) > df1$state[indx != 0] <- df2$newstate[indx] > df1 first state 1 jim tx 2 mick la 3 paul or 4 ron az

r merge data.frame match no-match

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -