【发布时间】:2020-02-06 22:26:41
【问题描述】:
我正在尝试在 R 的 for 循环中编写 if else 语句,如果 i == 向量中的任何值范围,则执行此操作,否则,执行其他操作。我知道当 if 语句中的条件的长度大于 1 时,只使用第一个值,但是,我想知道是否有办法解决这个问题,因为我使用的向量非常长(180 个值)并且为向量中的每个条件编写单独的 if 语句会非常混乱。我正在尝试完成的一个示例在下面输入。有没有办法只使用条件中的第一个值?
example<-c(1,2,3,4)
z<-c()
for (i in 1:10)
{
if (i==example) #if i == any of the values in example
{
z<-c(z,0) #add a 0 to the vector z
}else {z<-c(z,1)} #else add a 1
}
#resulting vector should have four zeros and six ones
【问题讨论】:
-
尝试使用
%in%运算符。即if (i %in% example)
标签: r if-statement