Victoria Chan - 5 months ago 29

R Question

Write a function which takes a matrix that can be coerces into a matrix; the function should return a matrix which is the same as the function argument, but every even number is not changed and odd number is doubled.

matrices

I'm very new to R. Can someone help me complete my codes:

`mx = matrix(c(1,1,3,5,2,6,-2,-1,-3), nrow = 3, byrow = TRUE)`

fun = function(mx){

for(i in mx){

if(i %% 2 == 0){

return(i)

}

else if(i %% 2 > 0){

return(2*i)

}

}

}

Answer

Don't need a function, just use the built-in function `ifelse`

:

```
mx <- ifelse(mx %% 2 == 0, mx, 2*mx)
```

Or, if you prefer to encapsulate it into a function:

```
fun = function(mx) {
ifelse(mx %% 2 == 0, mx, 2*mx)
}
res <- fun(mx)
## [,1] [,2] [,3]
##[1,] 2 2 6
##[2,] 10 2 6
##[3,] -2 -2 -6
```

**Explanation:**

`ifelse`

performs a vectorized comparison over all elements of the matrix mx to see if each element is even (i.e., `mx %% 2 == 0`

). For each element if this comparison condition is `TRUE`

, the next argument is returned, which in this case is just the value from that element in `mx`

. Otherwise, the last argument is returned, which is `2`

times the value from that element in `mx`

as you wish.