简体   繁体   English

R的for循环内的if-else语句

[英]if-else statement inside for loop for R

I've read through some of the if-else if question for for loop, but I cannot seem to solve what the problem is for my script. 我已经读过一些for循环的if-else if问题,但是我似乎无法解决脚本的问题。

type = numeric(length(r))

for (i in 1:10) {
    if ( ((s_mov[i] < s_rot[i]) & (e_rot[i] < e_mov[i])) | ((s_rot[i] < s_mov[i]) & (s_mov[i] < e_rot[i])) == TRUE) {
        type[i]=1
    } 
    else if ( ((s_doc[i] < s_rot[i]) & (e_rot[i] < e_doc[i]) == TRUE) {
        type[i]=2
    }
    else if ( ((s_rot[i] < e_mov[i]) & (s_doc[i] < e_rot[i])) | ((s_rot[i] < s_mov[i]) & (s_doc[i] < e_rot[i])) == TRUE) {
        type[i]=3
    }
}

or I've tried this way as well 或者我也尝试过这种方式

for (i in 1:10) {
    if ( ((s_mov[i] < s_rot[i]) & (e_rot[i] < e_mov[i])) | ((s_rot[i] < s_mov[i]) & (s_mov[i] < e_rot[i])) == TRUE) {
        type[i]=1
    } 
    else if ( ((s_doc[i] < s_rot[i]) & (e_rot[i] < e_doc[i]) == TRUE) {
        type <- replace(type, type[i],2
    }
    else if ( ((s_rot[i] < e_mov[i]) & (s_doc[i] < e_rot[i])) | ((s_rot[i] < s_mov[i]) & (s_doc[i] < e_rot[i])) == TRUE) {
        type <- replace(type, type[i],3
    }
}  

but I'm constantly getting 但我不断

Error: unexpected '{' in:

What's wrong? 怎么了?

I'm not sure but I think depending on the data, when all 1:10 satisfy first if statement, it writes 1 for all 10 elements, and rather than stooping, it continues and cause error. 我不确定,但是我认为,取决于数据,当所有1:10都首先满足if语句时,它将为所有10个元素写入1,而不是弯腰,而是继续并导致错误。

It looks like you're missing several closing brackets in different places. 好像您在不同的地方缺少几个右括号。 I highly recommend using a good IDE, such as RStudio, which has a side-benefit of highlighting the matching brackets. 我强烈建议您使用RIDE等出色的IDE,它具有突出显示匹配括号的好处。

Both the type <- replace... statements need a closing ) . 两种type <- replace...语句都需要结束)
Just by eyeballing, it looks like the first else if is missing a closing ) as well: 只是通过目测, else if还缺少一个) ,它也看起来像第一个:

else if ( ((s_doc[i] < s_rot[i]) & (e_rot[i] < e_doc[i]) == TRUE) {

you have 4 opening and only 3 closing brackets in there. 您有4个开孔,其中只有3个开孔括号。

I haven't checked the other statements, but you should. 我没有检查其他语句,但是您应该检查。

In the first example, your first else if has an extra ( . 在第一个示例中,您的第一个else if有一个额外的(

In the second example, your first else if has an extra ( , and your replace functions have no ) . 在第二个示例中,第一个else if具有一个额外的( ,而您的replace函数没有)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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