[英]R programming loop
I am just starting the R program.我刚刚开始 R 程序。 I have couple of questions.我有几个问题。 I want to create for loop.我想创建 for 循环。 For example;例如; I created like this.我是这样创建的。 But I want to, loop created every x value,但我想,循环创建每个 x 值,
result = result + 2*n+1
for x = -1 result = 0
for x = 0 result = 0
for x = 1 result = 3
for x = 2 result = 6
# etc, until
x = 9 result = 27
result = 0
vector<-c(-1:9)
for (x in vector){
print(x)
x = x+1
n = as.integer(1)
if (x<=0){
result= 1
} else{
result = result + 2*n+1
}
}
print(result)
Is this it?是这个吗? The special cases for x <= 0
force the code to predict the special case when x
already is above 0
, meaning, x == 1
. x <= 0
的特殊情况强制代码预测当x
已经大于0
时的特殊情况,即x == 1
。
n <- 1
vector <- -1:9
for (x in vector){
cat("x:", x, "\t")
if (x <= 0){
result <- 1
} else{
if(x == 1) result <- 0
result <- result + 2*n + 1
}
cat("result:", result, "\n")
}
#x: -1 result: 1
#x: 0 result: 1
#x: 1 result: 3
#x: 2 result: 6
#x: 3 result: 9
#x: 4 result: 12
#x: 5 result: 15
#x: 6 result: 18
#x: 7 result: 21
#x: 8 result: 24
#x: 9 result: 27
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.