我是R的新手,一直試圖弄清楚這一點。基本上我有一個數據框,和各種變量。我正在嘗試編寫一個函數,使我能夠爲我所擁有的許多不同的y
變量提供自定義圖形模板。我想下面的下面的代碼,但我遇到了這個錯誤:爲ggplot編寫函數
1: In eval(expr, envir, enclos) : NAs introduced by coercion
2: In aes_string(xvar[max(which(complete.cases(yvar)))], yvar[max(which(complete.cases(yvar)))], : NAs introduced by coercion
代碼工作,如果我直接和不添加變量通過函數。我相信這與功能如何將xvar
插入到as.numeric()
函數中有關。我不確定,但你們中的任何一個人都知道如何處理這個問題?
test <- function (Data, xvar, yvar){
# Plot data
plot <- ggplot(subset(Data,!is.na((yvar))), aes_string(xvar, yvar)) + geom_line(colour="darkblue") + theme_bw()
# Add Trendline for recent data
plot <- plot + geom_smooth(data=subset(Data, xvar > as.numeric(xvar)[max(which(complete.cases(yvar)))-8]), method = "lm")
# Label most recent data
plot + geom_text(data = Data, aes_string(xvar[max(which(complete.cases(yvar)))],
yvar[max(which(complete.cases(yvar)))],
label = as.numeric(yvar)[max(which(complete.cases(yvar)))],
hjust= -0.5, vjust = 0.5))
'aes_string'需要一個字符串。 'xvar [max(which(complete.cases(yvar)))'在這裏沒有意義。在ggplot2之外計算這個值。另外,不要在函數內部使用'subset'。這是文件警告這一點。 – Roland
非常感謝!我明白你的意思了! – Binggg