Home > front end >  How to replace a value with an if loop with 2 conditions in a dataframe?
How to replace a value with an if loop with 2 conditions in a dataframe?

Time:04-04

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.

CodePudding user response:

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
  • Related