Jim Jim - 1 month ago 6
R Question

R replace variable given multiple conditions

My data is organized as follows:

year company color car_total
2000 toyota red 873
2013 honda red 737
2012 nissan green 809
2002 toyota blue 429
2000 nissan green 861
2012 honda red 742
2009 toyota red 320
2010 ford yellow 319
2000 ford green 587
2011 nissan blue 777
2014 ford blue 32


I am trying to replace the values in columns given multiple conditions. Two situations:


  1. I would like to replace each
    car_total
    for rows of
    company == ford
    OR
    company == nissan
    with 0. What command would accomplish this?

  2. What if my constraints came from different columns? e.g. What if I wanted to replace any
    car_total
    which has its
    company
    == ford OR
    color
    == red with 0?


Answer

As you have seen from comments this can be done compactly as a standard selection. But sometimes logical vectors make things clearer.

Assuming your dataframe is called df

redcars <- df$color == "red"
fords <- df$company == "ford"
ford_or_nissan = fords | df$company == "nissan" # or alternatively
ford_or_nissan = df$company %in% c("ford","nissan")

This gives you three vectors you can use to select the desired rows

df$car_total[ford_or_nissan] <- 0
df$car_total[fords | redcars] <- 0

With logical operators, you can build up as complex a selection as you want.

Comments