Search code examples
rdataframeanalytics

IF statement in R. Add new elements in new column if conditions met


I'm trying to add a column in the data frame where the new element in the new column has the value of "1" if the conditions are met for that particular row.

To check the condition I am iterating through another reference data frame.

county_list = (df$county_name[df$wolves_present_in_county==1 & df$year==2015])

for (i in df$county_name) {
  for (j in county_list) {
    if (df$county_name[i]==county_list[j])
    {
      df$wolvein2015 = 1
      break
    }
  }
}

Error in Output Dataset


Solution

  • I think you can do what you want in base R. Here is an example using mtcars:

    cars <- mtcars
    cars$new <- ifelse(cars$cyl == 4 & cars$mpg > 30, 1, 0)
    

    The new column is added with 0/1's based on conditions of 2 other variables.

    BTW, because R is a vectorized paradigm, you should only use for loops as a last resort.