[英]multiple ifelse with and and or conditions in R
I have a dataset and I want to create a multiple ifelse statement. 我有一个数据集,我想创建一个多个ifelse语句。 I want to find out if this person/id lived in the big city (being london or paris) in the years 2011 and 2012. Any suggestions how I can get this with multiple ifelse?
我想知道这个人/身份证是否在2011年和2012年居住在大城市(伦敦或巴黎)。关于如何使用多个ifelse来获得此建议,有何建议?
id<- c(1,1,2,2,3)
location <- c('london', 'paris', 'london', 'kathmanadu','newyork')
year<- c(2011, 2010, 2012, 2011, 2010)
df<- data.frame(location, year)
df$bigcity<- ifelse(df$location=='london'| df$location=='paris' &
df$year==2011| df$year==2012, 1, 0)
I think by multiple ifelse you mean nested ifelse. 我认为用多个ifelse表示嵌套ifelse。 if that is the case, here is a solution
如果是这样,这是一个解决方案
df$bigcity <- ifelse(grepl("london|paris", df$location), ifelse(grepl("2011|2012", df$year), 1, 0), 0)
what I did here is, IF the first condition is true, place the second condition in TRUE parameter. 我在这里所做的是,如果第一个条件为true,则将第二个条件放在TRUE参数中。
With data.table it comes out as: 与data.table一起显示为:
library(data.table)
setDT(df)
df[,location := ifelse(location %in% c('paris','london') & year %in% c(2011,2012),1,0)]
id location year new_value
1: 1 london 2011 1
2: 1 paris 2010 0
3: 2 london 2012 1
4: 2 kathmanadu 2011 0
5: 3 newyork 2010 0
A dplyr
solution using filter
, since I think its much more readable than nested ifelse
使用
filter
的dplyr
解决方案,因为我认为它比嵌套ifelse
更具可读性
id<- c(1,1,2,2,3)
location <- c('london', 'paris', 'london', 'kathmanadu','newyork')
year<- c(2011, 2010, 2012, 2011, 2010)
df<- data.frame(id, location, year)
I want to find out if this person/id lived in the big city (being london or paris) in the years 2011 and 2012
我想知道这个人/身份证在2011年和2012年是否居住在大城市(伦敦或巴黎)
library(dplyr)
df %>%
filter(location %in% c('london', 'paris')) %>%
filter(year %in% c(2011, 2012))
# id location year
#1 1 london 2011
#2 2 london 2012
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.