Increment the content of a vector and re-save as the vector
Details
This function is very useful when writing complex codes involving loops. Apart from the for loop, this can be useful to quickly increment a variable located outside the loop by simply incrementing the variable by 1 or other numbers. Check in the example section for a specific use. Nonetheless, one may also choose to use this function in any other instance, as it's simple purpose is to increase the value of a variable by a number and then re-save the new value to that variable.
Examples
num1 <- sample(330:400,10)
num1#before increment
#> [1] 365 398 386 391 385 387 364 371 349 340
# increment num1 by 1
inc(num1)
num1 #after increment
#> [1] 366 399 387 392 386 388 365 372 350 341
# increment num1 by 5
num1 #before increment
#> [1] 366 399 387 392 386 388 365 372 350 341
inc(num1, add= 10)
num1 #after increment
#> [1] 376 409 397 402 396 398 375 382 360 351
#when used in loops
#add and compare directly
rnum = 10
inc(rnum) == 11 #returns TRUE
#> [1] TRUE
rnum #the variable was also updated
#> [1] 11
# use in a for loop
ynum = 1
for( i in c("scientist","dancer","handyman","pharmacist")){
message("This is the item number ")
message(ynum)
message(". For this item, I am a ")
message(i)
#decrement easily at each turn
plus(ynum)
}
#> This is the item number
#> 1
#> . For this item, I am a
#> scientist
#> This is the item number
#> 2
#> . For this item, I am a
#> dancer
#> This is the item number
#> 3
#> . For this item, I am a
#> handyman
#> This is the item number
#> 4
#> . For this item, I am a
#> pharmacist
#use in a repeat loop
xnum = 1
repeat{ #repeat until xnum is 15
message(xnum)
if(inc(xnum) == 15) break
}
#> 1
#> 2
#> 3
#> 4
#> 5
#> 6
#> 7
#> 8
#> 9
#> 10
#> 11
#> 12
#> 13
#> 14