我在 Rstudio 上使用 R 编写了以下代码。
# Calculate the current month as a numeric value
current_month <- as.numeric(format(Sys.Date(), "%m"))
# Create a sequence from 1 to the current month - 1
monthseq <- seq(1, current_month - 1)
# Convert these numbers to actual months in the current year
# Assuming we are using the current year for all months
current_year <- format(Sys.Date(), "%Y")
dates <- as.Date(paste(current_year, monthseq, "01", sep = "-"), "%Y-%m-%d")
# Format these dates to get abbreviated month names
month_list <- format(dates, "%b")
final_financials[is.na(final_financials)] <- 0 #changing all NA's to 0 to make it easier to report.
report <- final_financials %>% filter(Month %in% month_list &
Segment == "Revenues")
png(filename = "figs/ActualVBudget.png") #init the file to save the plot
report %>% ggplot(aes(Month, Actuals)) + geom_col() + geom_crossbar(
data = report,
aes(x = Month),
y = report$Budget,
ymin = report$Budget,
ymax = report$Budget,
color = "red"
)
dev.off() #closing and saving the file so I can access it
我对这几个月的工作方式并不满意,但我想要一些可扩展的东西。
我也对我编写情节的方式不满意,因为我必须传递数据两次,有更好的方法吗?
输入数据框丢失,但如果问题是如何创建
month_list
作为从一月到当月前一个月的月份(如果当前是一月,则为空向量)然后
d <- as.Date("2024-05-02")
seq(as.Date(cut(d, "year")), d, by = "month") |>
head(-1) |>
format("%b")
## [1] "Jan" "Feb" "Mar" "Apr"