decrease the content of a vector and re-save as the vector
Details
Similar to the inc and plus functions, the minus function is very useful when writing complex codes involving loops. Apart from the for loop, minus can be useful to quickly decrease the value of a variable located outside the loop by simply decreement the variable by 1 or other numbers. Check in the example section for a specific use. Given the scope, one may also choose to use this function in any other instances, as it's simple purpose is to decrease the value of a variable by a number and then re-save the new value to that variable.
Examples
num1 <- sample(5:150,10)
num1
#> [1] 110 146 131 23 81 78 135 73 59 98
# decrease num1 by 1
num1 #before decrease
#> [1] 110 146 131 23 81 78 135 73 59 98
minus(num1)
num1 #after decrease
#> [1] 109 145 130 22 80 77 134 72 58 97
# decrease num1 by 5
num1 #before decrease
#> [1] 109 145 130 22 80 77 134 72 58 97
minus(num1, minus = 5)
num1 #after decrease
#> [1] 104 140 125 17 75 72 129 67 53 92
#when used in loops
#add and compare directly
rnum = 23
minus(rnum) == 220 #returns FALSE
#> [1] FALSE
rnum #the variable was also updated
#> [1] 22
# use in a for loop
ynum = 100
for( i in c("teacher","student","lawyer","pharmacist")){
message("This is the item number ")
message(ynum)
message(". For this item, I am a ")
message(i)
#decrement easily at each turn
minus(ynum,3)
}
#> This is the item number
#> 100
#> . For this item, I am a
#> teacher
#> This is the item number
#> 97
#> . For this item, I am a
#> student
#> This is the item number
#> 94
#> . For this item, I am a
#> lawyer
#> This is the item number
#> 91
#> . For this item, I am a
#> pharmacist
#use in a repeat loop
xnum = 100
repeat{ #repeat until xnum is 85
message(xnum)
if(minus(xnum) == 85) break
}
#> 100
#> 99
#> 98
#> 97
#> 96
#> 95
#> 94
#> 93
#> 92
#> 91
#> 90
#> 89
#> 88
#> 87
#> 86