gpt4 book ai didi

R 使用高阶函数给矩阵中的所有行一个额外的身份

转载 作者:行者123 更新时间:2023-12-04 04:58:47 25 4
gpt4 key购买 nike

在 R 中,我有一个带有行名的矩阵,我想给每一行一个额外的标签/属性。也就是说,根据我测试的一些标准,我想使用 apply 或(一些高阶函数)遍历矩阵中的所有行并给每一行一个额外的标签/属性(什么是正确的 R这里的词汇?)。例如,我想将矩阵中的每一行标记为“红色”、“蓝色”或“白色”。

  • 如何使用高阶函数标记矩阵“红色”、“蓝色”或“白色”中的每一行?
  • 我该怎么做 1. 没有高阶函数而只有循环?

  • 非常感谢所有帮助。

    最佳答案

    想到了两个实现。
    (1) 使用 data.frame
    (2) 维护矩阵(更快)并有一个 sepeartet 向量用于索引

    (1) 使用 data.frame

     myDF <- as.data.frame(myMatrix)

    myDF$color <- apply(myDF, 1, ColoringFunction)

    # grab all the "red" ones
    myDF[myDF$color=="red", ]

    (2) 使用索引向量
     myMatrix # remains a matrix

    ColorIndex <- apply(myMatrix, 1, ColoringFunction)

    # grab all the "red" ones
    myMatrix[ColorIndex =="red", ]

    # to initialize the vector to a given value use:
    ColorIndex <- rep("green", nrow(myMatrix))

    哪里 myMatrix是你的原始数据, ColoringFunction(<matrix row>)是您用来确定颜色分配的函数。

    关于R 使用高阶函数给矩阵中的所有行一个额外的身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16403508/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com