我有一个dataframe,它包含以下列表列的结果:
水果
苹果,梨,香蕉
梨
香蕉,苹果
苹果、梨
西瓜,苹果,梨,香蕉
梨、西瓜
我想在中创建一个交叉矩阵--只为这一列,因此输出将显示哪些水果被紧密地列在一起。X和y轴都是基于这一列的。
发布于 2020-10-26 19:55:56
我认为你想得到的是协方差矩阵,即:
df %>%
mutate(.id=row_number()) %>%
unnest_longer(c(Fruits)) %>%
mutate(value = 1) %>%
pivot_wider(id_cols=.id, names_from=Fruits) %>%
select(-.id) -> result
# replacing NA s with 0 s
result[is.na(result)] <- 0
result
# A tibble: 6 x 4
Apple Pear Banana Watermelon
<dbl> <dbl> <dbl> <dbl>
1 1 1 1 0
2 0 1 0 0
3 1 0 1 0
4 1 1 0 0
5 1 1 1 1
6 0 1 0 1
result %>% cov
Apple Pear Banana Watermelon
Apple 0.26666667 -0.06666667 0.2 -0.06666667
Pear -0.06666667 0.16666667 -0.1 0.06666667
Banana 0.20000000 -0.10000000 0.3 0.00000000
Watermelon -0.06666667 0.06666667 0.0 0.26666667数据
df <- tibble(Fruits=list(list("Apple", "Pear", "Banana"),
list("Pear"),
list("Banana", "Apple"),
list("Apple", "Pear"),
list("Watermelon", "Apple", "Pear", "Banana"),
list("Pear", "Watermelon")))发布于 2020-10-27 02:56:58
接受Abdessabour Mtk所说的,并将其封装在带有YAML头的Rmarkdown代码中。
---
output:
html_document
---
```{r}图书馆(Tidyverse)
R码在这里
https://stackoverflow.com/questions/64541873
复制相似问题