0

I have a question regarding the combination of several ifelse functions in R. When attempting to run the following line, I get a result of only "Other".

standardized_object_codes <- ifelse(Spending_1$OBJECT_CODE %in% c("GG"), "Grants",
    ifelse(Spending_1$OBJECT_CODE %in% c("SW"),"Salaries and Wages",
    ifelse(Spending_1$OBJECT_CODE %in% c("DR"), "Retirement",
    ifelse(Spending_1$OBJECT_CODE %in% c("DO"), "Nonretirement",
    ifelse(Spending_1$OBJECT_CODE %in% c("PC"), "Contracts", "Other")))))

This is definitely not normal as my data contains all of the object codes that are listed in the function above (GG, SW, DR, DO and PC). Could you please help me out with what I am doing wrong?

Thanks a lot!

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
B.Tot
  • 23
  • 5

3 Answers3

0

As a follow-up to my comment above, you could try

standardized_object_codes <- with(Spending_1, dplyr::case_when(
    OBJECT_CODE == "GG" ~ "Grant",
    OBJECT_CODE == "SW" ~ "Salaries and Wages",
    OBJECT_CODE == "DR" ~ "Retirement",
    OBJECT_CODE == "DO" ~ "Nonretirement",
    OBJECT_CODE == "PC" ~ "Contracts",
    TRUE ~ "Other"))

Or create a lookup table and use match to match entries.

df.lookup <- data.frame(
    OBJECT_CODE = c("GG", "SW", "DR", "DO", "PC"),
    Description = c("Grant", "Salaries and Wages", "Retirement", "Nonretirement", "Contracts"),
    stringsAsFactors = F)

standardized_object_codes <- replace(
    x <- df.lookup$Description[match(Spending_1$OBJECT_CODE, df.lookup$OBJECT_CODE)], 
    is.na(x), "Other")
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

You can use factor labels:

lev = c("GG", "SW", "DR", "DO", "PC","others")
lab = c("Grant", "Salaries and Wages", "Retirement", "Nonretirement", "Contracts","others")

#Now change everything not in lev to "others"
newf = ifelse(Spending_1$OBJECT_CODE %in% lev, Spending_1$OBJECT_CODE, "others")

as.character(factor(newf, lev, lab)) #change all names at once
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

Your code appears to work when provided a vector in a data frame.

> Spending_1 <- data.frame(OBJECT_CODE = c("GG", "SW", "DR", "DO", "PC", "Other"))
> standardized_object_codes <- ifelse(Spending_1$OBJECT_CODE %in% c("GG"), "Grants",
                               ifelse(Spending_1$OBJECT_CODE %in% c("SW"),"Salaries and Wages",
                               ifelse(Spending_1$OBJECT_CODE %in% c("DR"), "Retirement",
                               ifelse(Spending_1$OBJECT_CODE %in% c("DO"), "Nonretirement",
                               ifelse(Spending_1$OBJECT_CODE %in% c("PC"), "Contracts", "Other")))))

> standardized_object_codes
[1] "Grants"             "Salaries and Wages" "Retirement"        
[4] "Nonretirement"      "Contracts"          "Other" 

If you're not getting the result you want, it may have to do with the way your data is structured, or how you are applying your code.