R错误:if循环中的if语句,意外“}”

时间:2013-08-14 23:10:26

标签: r

我试图运行这些代码,但卡住了..

a<-data.frame(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
n<-1
empty <- data.frame(stringsAsFactors=F)
while (n<=5) {
    if (sum((a[,2*n+3]), (a[,2*n+4])) == 13) {
        empty <-data.frame(cbind(empty, 3), n<-n+1
    } else {
        empty <-data.frame(cbind(empty, 2), n<-n+1
    }
}

这些是我得到的:

> a<-data.frame(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
> n<-1
> empty <- data.frame(stringsAsFactors=F)
> while (n<=5) {
+     if (sum((a[,2*n+3]), (a[,2*n+4])) == 13) {
+         empty <-data.frame(cbind(empty, 3), n<-n+1
+     } else {
Error: unexpected '}' in:
"        empty <-data.frame(cbind(empty, 3), n<-n+1
    }"
>         empty <-data.frame(cbind(empty, 2), n<-n+1
+     }
Error: unexpected '}' in:
"        empty <-data.frame(cbind(empty, 2), n<-n+1
    }"
> }
Error: unexpected '}' in "}"

我尝试了很多组合,即带走“{}”甚至将代码写入同一行,有或没有这些“{}”,但它们都不起作用。我的代码出了什么问题?

2 个答案:

答案 0 :(得分:2)

看起来你的括号不平衡:

empty <-data.frame(cbind(empty, 3), n<-n+1

答案 1 :(得分:2)

这是你想要的吗?

a<-data.frame(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
n<-1
empty <- c()
while (n<=5) {
cat("steps",n,"\n")
    if (sum((a[,((2*n)+3)]), (a[,((2*n)+4)])) == 13) {
cat("true in step",n,"\n")
        empty <-cbind(empty, 3)
        } else {
cat("false in step",n,"\n")
        empty <-cbind(empty, 2)                         
    }
    n<-n+1  # this should be after the if condition
}



  steps 1 
false in step 1 
steps 2 
false in step 2 
steps 3 
false in step 3 
steps 4 
false in step 4 
steps 5 
false in step 5 
> empty
     [,1] [,2] [,3] [,4] [,5]
[1,]    2    2    2    2    2