我使用我不完全理解的tail()
函数收到错误。我希望在最后一行大于0时打印图表,否则打印Have a nice day
数据:
dates <- seq(as.Date("2015-02-13"), as.Date("2015-02-22"), by = "days")
b <- c(1,1,1,1,2,2,3,3,3,0)
c <- c(20,30,26,20,30,40,5,10,4,0)
d <- c(11,2233,12,2,22,13,23,23,100,0)
df <- data.frame(dates,b,c,d)
a.plot<-plot(df)
test <- function(df) {
if(tail(df[2:ncol(df)], 1) > 0) { # check only last date
return(a.plot)
} else {
print("Have a nice day!")
}
}
test(df)
错误:
[1] "Have a nice day!"
Warning message:
In if (tail(df[2:ncol(df)], 1) > 0) { :
the condition has length > 1 and only the first element will be used
答案 0 :(得分:2)
你可以在你的尾巴上使用nrow。我还使返回创建了图而不是依赖于函数之外的值
见下面的功能:
test <- function(df) {
if(sum(tail(df[2:ncol(df)], 1)) > 0) { # check only last date
return(plot(df))
} else {
print("Have a nice day!")
}
}