我一直在试图解决这个问题,但不幸的是我对积分和R都很陌生。任何人都可以帮我弄清楚我在这里做错了什么吗?问题如下: Question 3
到目前为止,这是我的代码:
## Question 3
rm(list=ls())
## a)
X<-(2*(1:20))
X
## b)
Y<-rep(0,20)
Y
## c)
for (k in 1:20){
Y[k] <- k
if (k < 12){
Y[k]<-cos(3*k)
} else if (k >= 12) {
integral <- function(t) sqrt(t)
Y[k]<-integrate(integral, lower = 0, upper = k)
}
}
Y
这是我运行代码时的输出:
Warning messages:
1: In Y[k] <- integrate(integral, lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
2: In Y[k] <- integrate(integral, lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
3: In Y[k] <- integrate(integral, lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
4: In Y[k] <- integrate(integral, lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
5: In Y[k] <- integrate(integral, lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
6: In Y[k] <- integrate(integral, lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
7: In Y[k] <- integrate(integral, lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
8: In Y[k] <- integrate(integral, lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
9: In Y[k] <- integrate(integral, lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
> Y
[[1]]
[1] -0.9899925
[[2]]
[1] 0.9601703
[[3]]
[1] -0.9111303
[[4]]
[1] 0.843854
[[5]]
[1] -0.7596879
[[6]]
[1] 0.6603167
[[7]]
[1] -0.5477293
[[8]]
[1] 0.424179
[[9]]
[1] -0.2921388
[[10]]
[1] 0.1542514
[[11]]
[1] -0.01327675
[[12]]
[1] 27.71282
[[13]]
[1] 31.24811
[[14]]
[1] 34.92214
[[15]]
[1] 38.72984
[[16]]
[1] 42.66667
[[17]]
[1] 46.72854
[[18]]
[1] 50.91169
[[19]]
[1] 55.21273
[[20]]
[1] 59.62849
当我使用计算器检查结果时,我的b)值似乎不正确,我不知道为什么我收到c)的警告。我也不熟悉积分,所以我不知道我应该对这个问题有什么样的价值观。感谢您提供任何帮助!
答案 0 :(得分:0)
问题是,integrate(...)
正在为您提供list
,并且您希望在向量中替换它。这就是错误。
integral <- function(t) sqrt(t)
result <- integrate(integral, lower = 0, upper = 1)
is(result)
# [1] "integrate" "oldClass"
result$value
# [1] 0.6666667
这是您的问题的解决方案。你的第二行没有必要。
for (k in 1:20){
if (k < 12){
Y[k]<-cos(3*k)
} else if (k >= 12) {
integral <- function(t) sqrt(t)
result <- integrate(integral, lower = 0, upper = k)
Y[k] <- result$value
}
}