-4

Edited to make reproducible, I think.

I have a similar table to this:

UnitID <- c(177834,180203,222178,138558)
Year <- c(2019,2019,2019,2019)
EndowmentF <- c(108431567,NA,444076565,NA)
EndowmentG_ID<-c(177834,180203,222178,138558)
EndowmentG_YR <- c(2019,2019,2019,2019)
EndowmentG <- c(NA,1220803,NA,17251420)
Endow <- data.frame(UnitID,Year,EndowmentF,EndowmentG_ID,EndowmentG_YR,EndowmentG)

I attempt to create a new variable called Endowment because the original data was reported in two tables based on different reporting methods. When I use the following code I get an error and the variable isn't computed:

Endowments <- Endow %>% mutate(
  Endowment= if(UnitID=EndowmentG_ID && Year=EndowmentG_YR && is.na(EndowmentG))
  {EndowmentF} else {EndowmentG})

I get the following error in the console and am not sure what I have done wrong. Any help or advice would be great. I was able to get this to work in Excel using IF/AND Logic but not sure how to fix it in R.

Error: unexpected '=' in:
"Endowments <- Endow %>% mutate(
  Endowment= if(UnitID="
>   {EndowmentF} else {EndowmentG})
Error: unexpected 'else' in "  {EndowmentF} else"

2 Answers2

0

Try this chunk of code and I think the problem is you should use == instead of = for conditional phrases:

   Endowments <- Endow %>% mutate(
   if(UnitID == EndowmentG_ID && Year == EndowmentG_YR && is.na(EndowmentG)){
      Endowment = EndowmentF} else {
         Endowment = EndowmentG
         }
   )
ETeddy
  • 115
  • 5
-1

You may use ifelse since it is vectorized.

library(dplyr)

Endow <- Endow %>%
  mutate(Endowment = ifelse(UnitID == EndowmentG_ID & Year == EndowmentG_YR & 
                            is.na(EndowmentG), EndowmentF, EndowmentG))
Endow

#  UnitID Year EndowmentF EndowmentG_ID EndowmentG_YR EndowmentG Endowment
#1 177834 2019  108431567        177834          2019         NA 108431567
#2 180203 2019         NA        180203          2019    1220803   1220803
#3 222178 2019  444076565        222178          2019         NA 444076565
#4 138558 2019         NA        138558          2019   17251420  17251420
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213