gpt4 book ai didi

r - 得分与 R 共有的因素数

转载 作者:行者123 更新时间:2023-12-04 01:24:18 26 4
gpt4 key购买 nike

我正在处理一个棘手的问题。假设我有以下数据:

df <- data.frame(matrix(ncol = 0, nrow = 7))
df$x <- factor(c("blue","blue","red","red","green","green","black"))
df$y <- factor(c("A","B","A","C","B","C","A"))
df$z <- c(1998, 1998, 1998, 1998, 1999, 2000, 2001)

我们可以看到 A 和 B 有共同的蓝色,但没有红色或黑色。 A 和 C 有共同的红色,但没有蓝色、绿色或黑色。等等。

我想生成一个矩阵,根据字母 i,j 占据的所有颜色(但不包括任何一个字母未占据的颜色)的联合,对字母 i,j 共有的颜色比例进行评分。换句话说,对角线是字母 i 占据的颜色总数,非对角线是字母 i 与字母 j 对于所有 i,j

我可以为每一对 A、B 分别做这样的事情:

df.A <- df[df$x %in% unique(df$x[df$y=="A"]),] # number of rows occupied by A 

df.B <- df[df$x %in% unique(df$x[df$y=="B"]),] # number of rows occupied by B

length(df.A$y[df.A$y=="B"]) # number of A's rows occupied by B

length(df.A$y[df.A$y=="B"]) / (length(df.A$y[df.A$y=="A"])) # proportion of times B agrees with A; i.e. (B|A) / A

在这个例子中,我们发现A总共占用了三种颜色,B总共占用了两种颜色。其中,A和B只有一个共同点。在 A 占据的所有内容中(n=3,不是整个 n=6 的集合),B 仅重叠一个,比例为 0.333。

在我的实际数据中有数千行和数百个因子水平,因此不可能手动完成所有排列。但是我无法弄清楚如何编写一个函数来执行它,即使经过大量搜索也是如此。我认为必须有一个我忽略的直接解决方案。请帮忙!

更新:感谢@Ian Campbell 和@thelatemail,解决方案很简单:

t(table(df[,1:2])) %*% table(df[,1:2])

crossprod(table(df$x, df$y))

为了回答我自己的其余问题,我可以简单地通过以下方式获得我想要的比例:

x <- t(table(df[,1:2])) %*% table(df[,1:2])

x / diag(x)

最佳答案

当我可以将线性代数用于某事时,我会喜欢上它。

t(table(df[,1:2])) %*% table(df[,1:2])
y
y A B C
A 3 1 1
B 1 2 1
C 1 1 2

编辑:如@thelatemail 所述,还有一个内置(可能更快)函数:

crossprod(table(df$x, df$y))

A B C
A 3 1 1
B 1 2 1
C 1 1 2

关于r - 得分与 R 共有的因素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62164518/

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