0

I'm using coalesce to combine two numerical columns into one.

I have a few set of columns, lets say one being A and B, that I need to combine; Currently, I'm using coalesce, but I need the 2nd column to be prioritized: ie. if both A and B have a value, I need the new variable to have the value from Column B, not Column A. Can I do this using coalesce, because I know it takes the first value, or do I need another function (or should I rearrange the column, which is less desirable?)

   A        B      NewVarAB
   1                  1
   3        5         5

This is my code:

rawdata2 <- (rawdata2 %>% mutate(Leaseconcat=coalesce(Leasemonthlytotal, Lease_Cost1))
         %>% mutate(LicenseConcat=coalesce(LicenseMonthlyTotal, grosslicense1))
         %>% mutate(NWAconcat=coalesce(NWAMonthlytotal, NWAGross1))
      )
Pre
  • 111
  • 7
  • 2
    You can use `coalesce()`. The function will take the first non-missing value, so put Column B before Column A when calling the function: `coalesce(B,A)` – MrFlick Nov 23 '20 at 23:12
  • I did, this didn't work. I think it goes by the way the columns are arranged in the dataframe – Pre Nov 23 '20 at 23:13
  • It does not go by the order in the data frame. I'm sure of that. Please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that demonstrates your problem. Your sample code does not match your sample data. – MrFlick Nov 23 '20 at 23:14
  • 1
    Is the missing value B an `NA` or null, or is it something else? – Tim Biegeleisen Nov 23 '20 at 23:14
  • Sorry @MrFlick you're right this did work based on what I was asking, but I have another problem now. I'll create another question. Thanks for the help. – Pre Nov 23 '20 at 23:23

0 Answers0