Any suggestions on the best logic to create a new variable in a r data frame that is contingent on other variables in the dataframe?
Essentially, I have a type variable in one data frame that I want to overide in certian instances which are contained in a second dataframe. Below is some sample data:
#### original data frame
id=c(1,2,3,4,5,6)
type=c("O", "O", "G", "O", "G", "O")
qty=c(10,20,30,40,50,60)
df1=data.frame(id, type, qty)
#### new dataframe with type override
id=c(2,4)
type_override=c("G", "G")
df2=data.frame(id,type_override)
#### dataframe with both origional and override type
df3=merge(df1, df2, by=c("id"), all.x=TRUE)
#### create new type variable that uses "type" for all variables
#### unless "type_override" calls for a override
df3$type_new= ???????
I would like to use the type classification (i.e. “type_override”) in the second dataframe to override the type classification (i.e. “type” in the first dataframe.
I am an Excel user that is trying to make the transition to R, in Exel, I would just do something like:
type_newC1 = if(isna(type_overrideB1),typeA1,type_overrideB1)
Any assistance would be greatly appreciated.
If your df2 will be used with only a single type, you can get away with a single step: