Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom function for multiplying all odd values in matrix

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

mat <- matrix(sample(80), ncol = 10)

ifelse(mat %% 2 != 0, mat * 0.618, mat)

ifelse takes three arguments:

  1. the condition (in your case that the number is divisible by 2)

  2. the value to assign if the condition occurs

  3. the value to be assigned if the condition does not occur

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading