I'm very new to R, but I'm just looking to do a simple conditional reassignment to elements in a vector Y. However, I keep getting warning messages when the reassignments are dealing with integrals. Here is the complete code:
> rm(list=ls())
> Y <- c()
> for (k in 1:20) {
+ Y[k] <- k
+ }
> for (k in 1:20) {
+ if (Y[k] < 12) {
+ Y[k] <- cos(3 * k)
+ } else {
+ Y[k] <- integrate(function(t) sqrt(t), lower = 0, upper = k)
+ }
+ }
One of the warning messages:
Warning messages:
1: In Y[k] <- integrate(function(t) sqrt(t), lower = 0, upper = k) :
number of items to replace is not a multiple of replacement length
And the returned 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
Additionally, I'm a bit curious about why the output is broken up with two numbers for each element as well. Normally I'm used to vector output looking like this:
[1] 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
[20] 40
So any clarification about what I did wrong is highly appreciated.
Let me just show you how you can shorten your code:
Y <- numeric(20)
Y[1:12] <- cos(3 * (1:12))
Y[13:20] <- sapply(13:20, function (u) integrate(sqrt, lower = 0, upper = u)$value )
The result of:
integrate(function(t) sqrt(t), lower = 0, upper = k)
is a list.
you need to grab the first element of each list entry with [[1]]
prior to inserting into the Y
vector:
Y <- c()
#for (k in 1:20) { # This loop is unnecessary
# Y[k] <- k # as it will be overwritten
#} # with cos(3 * k) subsequently
for (k in 1:20) {
if (Y[k] < 12) {
Y[k] <- cos(3 * k)
} else {
Y[k] <- integrate(function(t) sqrt(t), lower = 0, upper = k)[[1]]
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.