使用 Tidyr 的 "gather" 和 Ggplot2 进行函数式编程,以实现更快速的可视化数据探索

Functional programming with Tidyr's "gather" and Ggplot2 for More Rapid Visual Data Exploration

下面的示例代码(使用来自 productplots 或 ggmosaic 的快乐数据集)让我可以快速可视化按快乐分解的各种分类变量(性别、婚姻、健康和学位) (快乐的)。为此,我必须从 "gather" 函数中分离出我想要作为条件的变量,在本例中为 "happy"。但是如果我想改变这个变量呢?或者创建另一个组合?我将不得不不断地重现下面的代码并更改变量。有没有更快的方法用一个函数来完成这个? purrr 包能以某种方式提供帮助吗?

Df1<-happy%>%
select(sex, happy, marital, health, degree)%>%
gather(key, value, -happy)%>%
count(happy, key, value)%>%
na.omit()%>%
mutate(perc=round(n/sum(n),2))

P<-ggplot(H5)+geom_col(aes(x=value,y=perc,fill=happy))+facet_wrap     
(~key,scales="free")+geom_text(aes
(x=value,y=perc,label=perc,group=happy),position=position_stack(vjust=.05))

我想要一个尽可能基于 Tidyverse 的解决方案。

只要您查看的是同一组列,就可以通过转换为您使用的每个函数的标准评估版本来将其包装在一个函数中。这是您的相同代码,只是在函数中调整为 运行:

plotLook <- function(thisCol = "happy"){
  happy %>%
    select(sex, happy, marital, health, degree) %>%
    gather_("key", "value"
            , names(.)[names(.) != thisCol]
            )%>%
    count_(c(thisCol, "key", "value")) %>%
    na.omit() %>%
    mutate(perc=round(n/sum(n),2)) %>%
    ggplot() + 
    geom_col(aes_string(x="value",y="perc",fill=thisCol)) +
    facet_wrap(~key,scales="free") +
    geom_text(aes_string(x="value",y="perc"
                         ,label="perc",group= thisCol)
              ,position=position_stack(vjust=.05))
}

现在这个:

plotLook("sex")

生成:

更好的是,您可以使用 lapply 一次性生成所有绘图:

lapply(c("sex", "happy", "marital", "health", "degree"), plotLook)

并将输出保存到 use/modify,或者让它们打印到屏幕上。