Home > Net >  Replace all occurrences of columns in a data frame
Replace all occurrences of columns in a data frame

Time:03-12

I have two columns Project ID and Project Number in my dataframe hpds_all_clean with NAs in them, and I'm trying to replace all NAs occurrences with "Undisclosed Project ID" and "Undisclosed Project Number". Here are some of my attempts which have the same error:

target of assignment expands to non-language object

Using gsub():

hpds_all_clean %>%
  filter(`Recipient Name-EN` == "Afghanistan") %>%
  hpds_all_clean$`Project Title - EN` = gsub("", "Undisclosed Project ID", hpds_all_clean$`Project Title - EN`) %>%
  hpds_all_clean$`Project Number/Numéro de projet` = gsub("", "Undisclosed Project Number", hpds_all_clean$`Project Number/Numéro de projet`)

Using paste0()

hpds_all_clean %>%
  filter(`Recipient Name-EN` == "Afghanistan") %>%
  paste0(hpds_all_clean, hpds_all_clean$`Project Title - EN`) = "Undisclosed Project ID" %>%
  paste0(hpds_all_clean, hpds_all_clean$`Project Number/Numéro de projet`) = "Undisclosed Project Number"

Any suggestion would be greatly appreciated. Thank you for your time!

CodePudding user response:

If these values are NA you can do

hpds_all_clean %>% 
  mutate(`Project Title - EN` = if_else(is.na(`Project Title - EN`),"Undisclosed Project ID",`Project Title - EN`),
         `Project Number/Numéro de projet` = if_else(is.na(`Project Number/Numéro de projet`),"Undisclosed Project Number",`Project Number/Numéro de projet`))

If these "NA" values are actually "", you would edit within the above to: if_else(`Project Title - EN` == ""), etc

CodePudding user response:

replace_na() in the tidyr package can help with this:

df <- data.frame(
  projectID = c('ABC', NA, "DEF", "HIJ", NA),
  projectNumber = c('LMN', "OPQ", "RST", NA, "UVW")
)

df %>% tidyr::replace_na(
  list(
    projectID = "Undisclosed Project ID",
    projectNumber = "Undisclosed Project Number"
  )
)

Output:

               projectID              projectNumber
1                    ABC                        LMN
2 Undisclosed Project ID                        OPQ
3                    DEF                        RST
4                    HIJ Undisclosed Project Number
5 Undisclosed Project ID                        UVW
  • Related