Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I replace an NA value in a colum for something if I have an specific value in another column?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading