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 to replace a value with an if loop with 2 conditions in a dataframe?

I have a dataset as follows:

Product  Transportation  Customs
 A       Air             Santamaria   
 B       Ocean           Limon
 C       Ocean           Limon
 D       Air             Limon 
 E       Air             Santamaria   
 F       Air             Limon

Based on logical knowledge of the data I’m using, I know that Transportation = Air & Customs = Limon is a combination impossible to happen. (Example: Row F).

So I need to create an if loop to change the value based on those two conditions. I was thinking that if value in column customs = "Limon" & value in column Transportation = "Air", replace value in column Transportation with "Ocen" However, I don’t know exactly how the syntax is for this code works.

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

>Solution :

a data.table approach

library(data.table)
DT <- fread("Product  Transportation  Customs
A       Air             Santamaria   
B       Ocean           Limon
C       Ocean           Limon
D       Air             Limon 
E       Air             Santamaria   
F       Air             Limon")

DT[Transportation == "Air" & Customs == "Limon",
   Transportation := "Ocean"][]
#    Product Transportation    Customs
# 1:       A            Air Santamaria
# 2:       B          Ocean      Limon
# 3:       C          Ocean      Limon
# 4:       D          Ocean      Limon
# 5:       E            Air Santamaria
# 6:       F          Ocean      Limon
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