【问题标题】:Function for matrix in R [closed]R中的矩阵函数[关闭]
【发布时间】:2016-10-13 19:41:15
【问题描述】:

我是 R 中的新手(非常新)。我正在努力制作一个应该采用矩阵 (old_matrix) 并返回新矩阵 (new_matrix) 的函数,但在 new_matrix 中,old_matrix 中的所有值都是prime 出现在 new_matrix 中时应乘以 2。所以新矩阵应该看起来和旧矩阵一样,但是如果旧矩阵出现素数,这个元素应该乘以 2。

我在想我应该从 for 循环开始,但我已经在苦苦思索如何让循环遍历矩阵的所有元素。感谢所有帮助我更接近实现此功能!

【问题讨论】:

  • 首先创建一个reproducible example 并显示您迄今为止尝试过的代码。在 R 中可能不需要循环,但向我们展示您到目前为止所做的工作会有所帮助。

标签: r function for-loop matrix


【解决方案1】:

numbers 包中的 isPrime 函数可能会有很大帮助

# 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2020-10-30
    • 1970-01-01
    相关资源
    最近更新 更多