[英]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.我正在尝试在数据框中添加一列,如果满足该特定行的条件,则新列中的新元素的值为“1”。
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
}
}
}
Here is an option with dplyr
这是
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:我认为你可以在 base R 中做你想做的事。这是一个使用 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.根据 2 个其他变量的条件,新列添加了 0/1。
BTW, because R is a vectorized paradigm, you should only use for
loops as a last resort.顺便说一句,因为 R 是一个向量化的范例,所以你应该只将
for
循环用作最后的手段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.