问题描述
我正在尝试为列创建所有组合的散点图:insulin
、sspg
、glucose
(mclust,糖尿病数据集,在 R 中),类为 colo( u)r。我的意思是 sspg 的胰岛素、葡萄糖的胰岛素和葡萄糖的 sspg。
我想用 tidyverse、purrr、映射和管道操作来做到这一点。我不能完全让它工作,因为我对 R 和函数式编程比较陌生。
当我加载数据时,我得到了列:类、葡萄糖、胰岛素和 sspg。我还使用 pivot_longer
来获取列:attr 和 value,但我无法绘制它,也不知道如何创建组合。
我假设最后会有一个 iwalk()
或 map2()
函数,我可能不得不使用 group_by()
和 nest()
以及 combn(.,m=2)
对于组合或类似的东西。但它可能会有一些我自己看不到的更简单的解决方案。
我的尝试是这样的:
library(mclust)
library(dplyr)
library(tibble)
data(diabetes)
diabTib <- tibble::as_tibble(diabetes)
plot <- diabTib %>%
pivot_longer(cols = !c(class),names_to = "attr",values_to = "value") %>%
group_by(attr) %>%
nest()
最后,当我执行绘图或管道期间作为副作用(?)时,屏幕上应该有三个绘图。
将不胜感激。
解决方法
实际上,您可以使用 base::plot
轻松实现这一点。
# load data
diabetes <- mclust::diabetes
# define vector of colors based on class in order of cases in dataset
colors <- c("Red","Green","Blue")[diabetes$class]
# make pair-wise scatter plot of desired variables colored based on class
plot(diabetes[,-1],col = colors)
由 reprex package (v2.0.0) 于 2021 年 6 月 15 日创建
,let response:
try {
response = await axios.post(url,body);
} catch (e) {
throw new Error('Something wrong');
}
有很多方法可以做到这一点,我可能会从这种方式开始,因为它更容易理解,而且你只能得到与组合一样多的图
library(mclust)
#> Package 'mclust' version 5.4.7
#> Type 'citation("mclust")' for citing this R package in publications.
library(tidyverse)
data("diabetes")
tbl <- tibble::as_tibble(diabetes)
combn(setdiff(names(tbl),"class"),2,simplify = F) %>% #get combinations as vectors
map(~ggplot(tbl,aes_string(.x[[1]],.x[[2]],color = "class")) + geom_point())
#> [[1]]
#>
#> [[2]]
如果要绘制所有组合但在一个图形中,则需要 #>
#> [[3]]
。
这就是我将如何进行计算
tidyr
由 reprex package (v2.0.0) 于 2021 年 6 月 15 日创建