使用 ggplot 找不到使用 Mutate 创建的变量
Variable Created With Mutate Not Found With ggplot
R 新手。
我用 dplyr::mutate() 创建了一个新变量,当我 运行 代码时,我在 df 输出中看到了值,但是当我尝试用 ggplot 绘制它时,我收到对象未找到错误。我究竟做错了什么?谢谢
按预期工作:
mutate(avg_inv = (inv_total / sr_count))
此处错误:
# Plot avg invoice
p <- ggplot(df1, aes(x = Date_Group, y = avg_inv) ) +
geom_bar(stat = "identity", position="dodge")
p
错误信息:
Error in eval(expr, envir, enclos) : object 'avg_inv' not found
我认为您可能没有保存 mutate 的结果,因此即使结果打印到您的控制台,它也不适用于 ggplot2。
尝试:
df1 <- df %>% mutate(avg_inv = (inv_total / sr_count))
p <- ggplot(df1, aes(x = Date_Group, y = avg_inv) ) +
geom_bar(stat = "identity", position="dodge")
p
这个怎么样;在这里,我在对 ggplot 的函数调用中计算附加变量。这让我省去了临时变量来保存临时结果的麻烦,而且也没有错误。
data("airquality")
library(ggplot2)
library(dplyr)
p<- ggplot(airquality %>%
mutate(somevar=(Month/Day)), aes(x = somevar) ) +
geom_histogram(position = "stack", stat = "bin", binwidth = 5)
print(p)
R 新手。 我用 dplyr::mutate() 创建了一个新变量,当我 运行 代码时,我在 df 输出中看到了值,但是当我尝试用 ggplot 绘制它时,我收到对象未找到错误。我究竟做错了什么?谢谢
按预期工作:
mutate(avg_inv = (inv_total / sr_count))
此处错误:
# Plot avg invoice
p <- ggplot(df1, aes(x = Date_Group, y = avg_inv) ) +
geom_bar(stat = "identity", position="dodge")
p
错误信息:
Error in eval(expr, envir, enclos) : object 'avg_inv' not found
我认为您可能没有保存 mutate 的结果,因此即使结果打印到您的控制台,它也不适用于 ggplot2。 尝试:
df1 <- df %>% mutate(avg_inv = (inv_total / sr_count))
p <- ggplot(df1, aes(x = Date_Group, y = avg_inv) ) +
geom_bar(stat = "identity", position="dodge")
p
这个怎么样;在这里,我在对 ggplot 的函数调用中计算附加变量。这让我省去了临时变量来保存临时结果的麻烦,而且也没有错误。
data("airquality")
library(ggplot2)
library(dplyr)
p<- ggplot(airquality %>%
mutate(somevar=(Month/Day)), aes(x = somevar) ) +
geom_histogram(position = "stack", stat = "bin", binwidth = 5)
print(p)