【问题标题】:Problem with count (dplyr) within function函数内的计数(dplyr)问题
【发布时间】:2020-03-29 09:07:20
【问题描述】:

我编写了一段代码,我想在不同的变量上运行

#ggplot frequency table
marso <- some_dataset %>%
  count(some_variable)


##ggplot arrange
taart_marso <- marso %>%
  arrange(desc(some_variable)) %>%
  mutate(prop = round(n*100/sum(n), 1),
         lab.ypos = cumsum(prop) - 0.5*prop)
head(taart_marso, 4)

##ggplot piechart
ggplot(taart_marso, aes(x = "", y = prop, fill = some_variable)) +
  geom_bar(width = 1, stat = "identity", color = "white") +
  geom_text(aes(y = lab.ypos, label = n), color = "black", x=1.4)+
  coord_polar("y", start = 0)+
  theme_void()

我将上面的内容粘贴到一个函数中,并尝试使用相同的变量和数据集调用该函数

piechart <- function(dataset, variable) {


  mar <- dataset %>%
  count(variable)

taart_mar <- mar %>%
  arrange(desc(variable)) %>%
  mutate(prop = round(n*100/sum(n), 1),
         lab.ypos = cumsum(prop) - 0.5*prop)

ggplot(taart_mar, aes(x = "", y = prop, fill = variable)) +
  geom_bar(width = 1, stat = "identity", color = "white") +
  geom_text(aes(y = lab.ypos, label = n), color = "black", x=1.4)+
  coord_polar("y", start = 0)+
  theme_void()

}

piechart("some_dataset", "some_variable")

如果我这样做,我会收到以下错误:

UseMethod("group_by_") 中的错误: 'group_by_' 没有适用的方法应用于“字符”类的对象

谁能帮忙?

【问题讨论】:

  • 为什么x = ""ggplot

标签: r group-by dplyr count tidyverse


【解决方案1】:

使用tidyverse,如果我们传递一个不带引号的参数,我们可以使用{{}}

piechart <- function(dataset, variable) {


   mar <- dataset %>%
              count({{variable}})

   taart_mar <- mar %>%
                  arrange(desc({{variable}})) %>%
                  mutate(prop = round(n*100/sum(n), 1),
                         lab.ypos = cumsum(prop) - 0.5*prop)

   ggplot(taart_mar, aes(x = "", y = prop, fill = {{variable}})) +
         geom_bar(width = 1, stat = "identity", color = "white") +
        geom_text(aes(y = lab.ypos, label = n), color = "black", x=1.4)+
        coord_polar("y", start = 0)+
        theme_void()

   }



piechart(mtcars, vs)

注意:不应引用数据集对象,因为它可能导致使用get 来提取值,并且可能会产生不必要的错误。此外,aes 中的 x = "" 也不清楚。因此,请确保在必要时更改该部分


如果我们需要将带引号的字符串作为变量名传递,请将其转换为 symbol 和 ensym 并计算 (!!)

piechart <- function(dataset, variable) {

   variable <- rlang::ensym(variable)
   mar <- dataset %>%
              count(!!variable)

   taart_mar <- mar %>%
                  arrange(desc(!!variable)) %>%
                  mutate(prop = round(n*100/sum(n), 1),
                         lab.ypos = cumsum(prop) - 0.5*prop)
    ggplot(taart_mar, aes(x = "", y = prop, fill = !!variable)) +
       geom_bar(width = 1, stat = "identity", color = "white") +
       geom_text(aes(y = lab.ypos, label = n), color = "black", x=1.4)+
      coord_polar("y", start = 0)+
      theme_void()

   }



piechart(mtcars, "vs")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多