Using tidyr I want to modify a dataframe. Basically in this dataframe I have a column with different type of products: Fruits, Vegetables, Meat, etc... Let's call it the "Group" column In the same dataframe I have another column with the label of the product: Fruits and Vegetables products, Farm products, Fresh products... Let's call it the "Label"column.
What I'm trying to do is to replace the NA values of the Group column depending on the result of the Label column. For example: if the Label column shows "Farm products" then I want to replace the NA value of the Group column by the value "Milk". While if the Label column shows "Fruits and Vegetables products", I want the NA value of the Group column to take the value "Vegetables".
For this I've been trying to use the following code:
data_ES$Group <- data_ES$Group %>%
replace_na('Vegetables', if(data_ES$Label = "Fruits and Vegetables products"))
Of course this doesn't work because is just the intuition I have, I'm very new at programming.
Can somebody give me hints or ideas please?
CodePudding user response:
I coded a little example, for what I guess is what you are searching for:
library(tidyverse)
df <- tibble(Group = c(NA,"Fruits","Vegetables",NA,"Meat"),
Label = c("Fruits and Vegetables products",
"Fruits and Vegetables products",
"Fruits and Vegetables products",
"Farm products","Farm products" ))
df_replaced <- df %>% mutate(Group = case_when(Label == "Fruits and Vegetables products" & is.na(Group)
~ "Vegetables",
Label == "Farm products" & is.na(Group) ~ "Milk",
TRUE ~ Group))