I tried to run a couple of for-loops inside a function in order to get a couple of vectors, but it didn't work:
x_vec <- seq(-10, 10, .1)
y_vec <- seq(-10, 10, .1)
first_dim <- NA
second_dim <- NA
fgradient <- function(x, y) {
for (i in seq_along (x)) {
first_dim[i] <- (2 * (i - 2))
}
for (i in seq_along (y)) {
second_dim[i] <- (4 * i)
}
}
Here fgradient (x_vec, y_vec)
doesn't obtain the two vectors first_dim
and second_dim
. However, if I run the two for-loops separately outside the function, they do work and I get the two vectors. What am I missing? Thanks so much!
CodePudding user response:
We need to return
as a list
as there can be only return
object and if we don't specify it will be last evaluated expression. Also, instead of creating the 'first_dim', 'second_dim' outside the function, create it inside and also a vector with pre-specified length i.e. the length
of 'x' and 'y' input
fgradient <- function(x, y) {
first_dim <- numeric(length(x))
second_dim <- numeric(length(y))
for (i in seq_along (x)) {
first_dim[i] <- (2 * (i - 2))
}
for (i in seq_along (y)) {
second_dim[i] <- (4 * i)
}
return(list(first_dim = first_dim, second_dim = second_dim))
}
-testing
> fgradient(x_vec, y_vec)
$first_dim
[1] -2 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66
[36] 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 104 106 108 110 112 114 116 118 120 122 124 126 128 130 132 134 136
[71] 138 140 142 144 146 148 150 152 154 156 158 160 162 164 166 168 170 172 174 176 178 180 182 184 186 188 190 192 194 196 198 200 202 204 206
[106] 208 210 212 214 216 218 220 222 224 226 228 230 232 234 236 238 240 242 244 246 248 250 252 254 256 258 260 262 264 266 268 270 272 274 276
[141] 278 280 282 284 286 288 290 292 294 296 298 300 302 304 306 308 310 312 314 316 318 320 322 324 326 328 330 332 334 336 338 340 342 344 346
[176] 348 350 352 354 356 358 360 362 364 366 368 370 372 374 376 378 380 382 384 386 388 390 392 394 396 398
$second_dim
[1] 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100 104 108 112 116 120 124 128 132 136 140
[36] 144 148 152 156 160 164 168 172 176 180 184 188 192 196 200 204 208 212 216 220 224 228 232 236 240 244 248 252 256 260 264 268 272 276 280
[71] 284 288 292 296 300 304 308 312 316 320 324 328 332 336 340 344 348 352 356 360 364 368 372 376 380 384 388 392 396 400 404 408 412 416 420
[106] 424 428 432 436 440 444 448 452 456 460 464 468 472 476 480 484 488 492 496 500 504 508 512 516 520 524 528 532 536 540 544 548 552 556 560
[141] 564 568 572 576 580 584 588 592 596 600 604 608 612 616 620 624 628 632 636 640 644 648 652 656 660 664 668 672 676 680 684 688 692 696 700
[176] 704 708 712 716 720 724 728 732 736 740 744 748 752 756 760 764 768 772 776 780 784 788 792 796 800 804