I am trying to code a function in R which takes one argument (matrix) and multiply all odd values in it by 0.618.
This is what I got so far, but it is my first time working with R matrixes and not sure how to replace values in for loop, or if it’s better to do it after multiplying numbers.
>Solution :
Try this:
mat <- matrix(sample(80), ncol = 10)
ifelse(mat %% 2 != 0, mat * 0.618, mat)
ifelse
takes three arguments:
-
the condition (in your case that the number is divisible by 2)
-
the value to assign if the condition occurs
-
the value to be assigned if the condition does not occur