R %in%(';in';运算符)和&|(';或';运算符)一起用于分离混合在一起的数据集

R %in%(';in';运算符)和&|(';或';运算符)一起用于分离混合在一起的数据集,r,R,我想通过进入时段来区分进入门店的客户:在t1/t2/t3(不同时间)之后进入的客户。以下数据是在时间范围结束之前所有客户的数据 t1<-c(1:10) # at end of period t1, t2<-c(1:7,12:15) #at the end of t2, id 1:7 from t1 stayed in the store and the rest of peopel from t1 left. but new customers with id 12:15 en

我想通过进入时段来区分进入门店的客户:在t1/t2/t3(不同时间)之后进入的客户。以下数据是在时间范围结束之前所有客户的数据

t1<-c(1:10)   # at end of period t1, 
t2<-c(1:7,12:15) #at the end of t2, id 1:7 from t1 stayed in the store and the rest of peopel from t1 left. but new customers with id 12:15 entered
t3<-c(3:9,12:14,20:25) # at end of t3, some in t1 stay and some in t2 stay and new people came.

enter1<-t1
enter2<-t2[!(t2 %in% t1)]
enter3<-t3[!(t3%in%t1||t3%in% t2)]  
也许这有帮助

 t3[!t3 %in% union(t1, t2)]
或者使用
|
而不是
|

 t3[!(t3%in%t1|t3%in% t2)]  
根据
?“| |”

|和| |表示逻辑或。较短的形式按元素执行 比较的方式与算术运算符基本相同。越长 表单从左到右计算,只检查每个表单的第一个元素 矢量。评估仅在确定结果之前进行。这个 较长的形式适用于编程控制流,通常 在if条款中优先

如果我们检查输出

t3%in%t1|t3%in% t2
#[1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
t3%in%t1||t3%in% t2 
#[1] TRUE
仅返回单个TRUE元素。因此,求反(
)将返回
FALSE

 !(t3%in%t1||t3%in% t2)
 #[1] FALSE
如果我们用它来子集向量,我们将得到

  t3[!(t3%in%t1||t3%in% t2)]
  #integer(0)
也许这有帮助

 t3[!t3 %in% union(t1, t2)]
或者使用
|
而不是
|

 t3[!(t3%in%t1|t3%in% t2)]  
根据
?“| |”

|和| |表示逻辑或。较短的形式按元素执行 比较的方式与算术运算符基本相同。越长 表单从左到右计算,只检查每个表单的第一个元素 矢量。评估仅在确定结果之前进行。这个 较长的形式适用于编程控制流,通常 在if条款中优先

如果我们检查输出

t3%in%t1|t3%in% t2
#[1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
t3%in%t1||t3%in% t2 
#[1] TRUE
仅返回单个TRUE元素。因此,求反(
)将返回
FALSE

 !(t3%in%t1||t3%in% t2)
 #[1] FALSE
如果我们用它来子集向量,我们将得到

  t3[!(t3%in%t1||t3%in% t2)]
  #integer(0)

您还可以使用
setdiff
来避免有点笨拙的
x[!x%in%y]
构造:

enter3 <- t3[!((t3 %in%t1) | (t3%in% t2))] # using akrun's recommendation  
e2 = setdiff(t2, t1)
e3 = setdiff(t3, union(t1, t2))
identical(enter2, e2)
# [1] TRUE
identical(enter3, e3)
# [1] TRUE

enter3您还可以使用
setdiff
来避免有点笨拙的
x[!x%in%y]
构造:

enter3 <- t3[!((t3 %in%t1) | (t3%in% t2))] # using akrun's recommendation  
e2 = setdiff(t2, t1)
e3 = setdiff(t3, union(t1, t2))
identical(enter2, e2)
# [1] TRUE
identical(enter3, e3)
# [1] TRUE
enter3