1

I am needing to see how to update one column in a data frame where the employeeID matches that of another data frame.

For example:

df1 > 

empID     salary
1         10000
2         15000
3         0

df2 >

empID     salary2
1         10000
2         15000
3         20000    

I am needing to see how to update it where df1$salary = 0, then update it where df1$empID = df2$empID.

I tried this but received "No such column: salary2" error :

df1$salary <- ifelse(df1$salary == 0,sqldf("UPDATE df1 SET salary = salary2 WHERE df1.empID = df2.empID"),df1$salary)
1
  • In SQL update updates a table rather than returning a value. You need sqldf(c("update ...", "select * from df1")) to actually return something or else instead of using update use the appropriate SQL select statement. Commented May 31, 2019 at 14:55

2 Answers 2

2

Here is another option with merge,

transform(merge(df1, df2, by = 'empID'), 
               salary = replace(salary, salary == 0, salary2[salary == 0]), 
               salary2 = NULL)

#  empID salary
#1     1  10000
#2     2  15000
#3     3  20000

You can also use ifelse instead of replace for salary, i.e.

salary = ifelse(salary == 0, salary2, salary)
Sign up to request clarification or add additional context in comments.

Comments

1

We could do

#find empID in df1 where salary is 0
inds <- df1$empID[df1$salary == 0]

#match empID with df2 and get respective salary and update df1
df1$salary[inds] <- df2$salary2[match(inds, df2$empID)]
df1
#  empID salary
#1     1  10000
#2     2  15000
#3     3  20000

This should also work if you have multiple entries with 0 in df1.

We can do the same using ifelse like

ifelse(df1$salary == 0, df2$salary2[match(df1$empID, df2$empID)], df1$salary)

2 Comments

I see, is there any way I can implement this within my ifelse statement though? There is other conditions I am checking for as well with the real dataframe that I did not include in my sample code.
@jwalls91 updated the post using ifelse approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.