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] 350 383 336 366 397 363 373 344 362 349
# increment num1 by 1
inc(num1)
num1 #after increment
#> [1] 351 384 337 367 398 364 374 345 363 350
# increment num1 by 5
num1 #before increment
#> [1] 351 384 337 367 398 364 374 345 363 350
inc(num1, add= 10)
num1 #after increment
#> [1] 361 394 347 377 408 374 384 355 373 360
#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