简体   繁体   中英

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

Here is an option with dplyr

library(dplyr)
df %>%
     mutate(wolvein2015 = +((year == 2015 & !is.na(year)) &  
         as.logical(wolves_present_in_county) & !is.na(wolves_present_in_county)))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM