-2

I'm new (very new) in R. I'm struggling with making a function that's supposed to take a matrix (old_matrix) and return a new matrix (new_matrix), but in new_matrix all values in old_matrix that is a prime should be multiplied by 2 when it appears in new_matrix. So the new matrix should look the same as the old matrix, but where a prime occurs in old, this element should be multiplied by 2.

I'm thinking that I should start out with a for loop, but I'm already struggling with how to make the loop go through all elements of the matrix. I appreciate all the help I can get to get closer to making this function!

yoman
  • 33
  • 4
  • Start by making a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and show what code you've tried so far. Chances are in R a loop won't be necessary but showing us what you've done so far will help. – MrFlick Oct 13 '16 at 19:44

1 Answers1

1

The isPrime function in the numbers package could be a big help

# Start by creating an example to work with
old_matrix <- matrix(sample.int(100, 25), 5, 5)
# Create your new matrix and determine which numbers are prime
new_matrix <- old_matrix
primeVals <- numbers::isPrime(old_matrix)
# Index into the matrix using the prime value indicator and multiply by 2
new_matrix[primeVals] <- new_matrix[primeVals]*2
Barker
  • 2,074
  • 2
  • 17
  • 31