gpt4 book ai didi

r - 在 R 中向量化二维函数

转载 作者:行者123 更新时间:2023-12-02 21:54:41 26 4
gpt4 key购买 nike

我有一些真实的和预测的标签

truth <- factor(c("+","+","-","+","+","-","-","-","-","-"))
pred <- factor(c("+","+","-","-","+","+","-","-","+","-"))

我想构建混淆矩阵。我有一个适用于一元元素的函数

f <- function(x,y){ sum(y==pred[truth == x])}

然而,当我将它应用到外部积来构建矩阵时,R 似乎不高兴。

outer(levels(truth), levels(truth), f)
Error in outer(levels(x), levels(x), f) :
dims [product 4] do not match the length of object [1]

R 中推荐的策略是什么?

我总是可以处理更高阶的东西,但这看起来很笨拙。

最佳答案

我有时也无法理解 outer 哪里出了问题。对于此任务,我将使用表函数:

> table(truth,pred)   # arguably a lot less clumsy than your effort.
pred
truth - +
- 4 2
+ 1 3

在本例中,您将测试多值向量是否与标量“==”。

关于r - 在 R 中向量化二维函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17958122/

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