我有一个看起来像这样的数据框:
Fruit Colour
Apple Red
Apple Green
Cherry Red
Lemon Yellow
Banana Yellow
Blueberry Purple
Grapes Purple
Grapes Green
并且想要一个看起来像这样的矩阵:
Apple Cherry Lemon Banana Blueberry Grapes
Apple 0 1 0 0 0 1
Cherry 1 0 0 0 0 0
Lemon 0 0 0 1 0 0
Banana 0 0 1 0 0 0
Blueberry 0 0 0 0 0 1
Grapes 1 0 0 0 1 0
对应于color列中的行之间共享值的数量。
我已经尝试过这样的事情:
df1 <- dcast(fruit_frame, Fruit~Colour)
哪个给我一个数据框,其颜色为列,水果为行,每种颜色的出现次数,但这并不是我想要的。在R或python中有简单的方法吗?
先谢谢您。
答案 0 :(得分:3)
R
中的一个选项是
out <- tcrossprod(table(fruit_frame))
diag(out) <- 0