我已经多次运行下面的脚本并且它一直工作到今天早上,当它突然产生错误消息时:
(terms.formula(formula, data = data) 中的错误:'data' 参数类型错误。
我没有改变任何东西,我需要找出为什么它突然似乎不起作用。以前对类似问题的回答没有帮助。
我的数据:
DPUT(harvest2)
structure(list(Year = c(1971, 1972, 1973, 1974, 1975, 1976, 1977,
1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988,
1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016), Count = c(750, 757, 592,
693, 667, 757, 719, 670, 733, 796, 923, 921, 944, 1010, 825,
762, 825, 844, 809, 830, 768, 823, 749, 675, 700, 637, 708, 697,
754, 694, 636, 717, 786, 731, 769, 732, 710, 610.5, 593, 529,
664, 788, 731, 644, 653, 656), SexRat = c(1.91812865497076, 2.34567901234568,
1.69178082191781, 1.46766169154229, 1.30396475770925,
1.4364406779661, 1.32098765432099, 1.48584905660377, 1.5906976744186,
1.91414141414141, 1.48905109489051, 1.61382113821138, 1.52380952380952,
1.87777777777778, 1.75438596491228, 1.6695652173913, 1.81566820276498,
1.79295154185022, 1.85024154589372, 1.75446428571429, 1.83163265306122,
1.92857142857143, 1.76635514018692, 1.5, 2.26190476190476, 1.76704545454545,
2.38125, 1.80924855491329, 2.33333333333333, 1.81182795698925,
2.20446096654275, 2.02790697674419, 2.1140350877193, 2.05, 2.20183486238532,
1.90983606557377, 2.02262443438914, 1.75116279069767, 1.86842105263158,
1.87951807228916, 2.08542713567839, 2.01724137931034, 1.95833333333333,
1.81165919282511, 2.12135922330097, 1.97260273972603)), class = "data.frame",
row.names = c(NA, -46L))
我的脚本:
# Function for the equation
lm_eqn = function(df){
m = lm(y ~ poly(x, 3), df) #3rd degree polynomial
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(coef(m)[1], digits = 2),
b = format(coef(m)[2], digits = 2),
r2 = format(summary(m)$r.squared, digits = 4)))
as.character(as.expression(eq))
}
# Make the plot
library(ggplot2)
ggplot(harvest2, aes(x = Year, y = Count)) +
scale_y_continuous(minor_breaks = seq(500, 1100, by = 50),
breaks = seq(500, 1100, by = 100),
limits = c(500, 1100), expand = c(0, 0)) +
scale_x_continuous(minor_breaks = seq(1970, 2018, by = 1),
breaks = seq(1970, 2018, by = 5), limits = c(1970, 2018)) +
geom_point(stat = 'identity', size=2) +
stat_smooth(method = "lm", se = TRUE, fill = NA, size = 1.3,
formula = y ~ poly(x, 3, raw = TRUE), col = "red") +
annotate("text", x = 1975, y = 1075, label = lm_eqn(df),
hjust = 0, size = 3.5, parse = TRUE) +
xlab(" ") +
ylab("Count") +
theme_light() +
ggtitle(" ")
非常感谢任何帮助。