kur*_*dtc 7 plot r function range na
我想在data.frame中xy为每个组绘制数据(定义方式ID).当1946年之前的一年是一组时,plot 2应该执行.当年份在1946年至2014年之间时,plot1应该执行.
我的问题:没有NA值就可以正常工作,但由于我有数据空白,我依靠NAs来定义这些数据空白.这就是我收到错误的原因:error in plot.window(need finite 'ylim' values).我试图在y轴放入finite=T,plot1但这会产生subscript out of bounds错误.有没有办法解决这个问题,图形是否正确绘制?
以下是我的代码:它很长但是大部分代码都包含plot()我依赖的选项.
# read in sample data and split it up by group (defined by ID)
xy <- data.frame(NAME=c("NAME2","NAME2","NAME2","NAME2","NAME2","NAME3","NAME3","NAME3","NAME3","NAME5","NAME5","NAME5","NAME5"), ID=c(48,48,48,48,48,32,32,32,32,67,67,67,67),YEAR=c(1981,1983,1984,1988,1989,1984,1984,1988,1988,1899,1933,1948,1958),VALUE=c(0,205,-570,0,-310,-3680,-3680,NA,-3680,0,NA,13,-98))
ind <- split(x = xy,f = xy[,'ID'])
# Plot Scenario 1: if only years between 1946 and 2014 are present for each group do this:
plot1 <- function(x) {
fname <- paste0(x[1, 'ID'], '.png')
png(fname, width=1679, height=1165, res=150)
par(mar=c(6,8,6,5))
plot(x = c(1946, 2014),
y = range(x$VALUE),
type='n',
main=x[1, 'NAME'],
xlab="Time [Years]",
ylab="Value")
axis(2, at = seq(-100000, 100000, 500), cex.axis=1, labels=FALSE, tcl=-0.3)
points(ind[[i]][,c('YEAR','VALUE')], type="l", lwd=2)
points(ind[[i]][,c('YEAR','VALUE')], type="p", lwd=1, cex=1, pch=21, bg='white')
abline(h=0)
dev.off()
}
# Plot Scenario 2 if years under 1946 are present do this:
plot2 <- function(x) {
fname <- paste0(x[1, 'ID'], '.png')
png(fname, width=1679, height=1165, res=150)
par(mar=c(6,8,6,5))
plot(x[,c('YEAR','VALUE')],
type='n',
main=x[1, 'NAME'],
xlab="Time [Years]",
ylab="Value [mm]")
axis(2, at = seq(-100000, 100000, 500), cex.axis=1, labels=FALSE, tcl=-0.3)
points(ind[[i]][,c('YEAR','VALUE')], type="l", lwd=2)
points(ind[[i]][,c('YEAR','VALUE')], type="p", lwd=1, cex=1, pch=21, bg='white')
abline(h=0)
dev.off()
}
# Execute functions
lapply(ind, function(x) ifelse(any(x$YEAR < 1946 & x$YEAR < 2014), plot2(x), plot1(x)))
Run Code Online (Sandbox Code Playgroud)
在 中plot1,更改y = range(x$VALUE)为y = range(x$VALUE, na.rm=TRUE)以删除NA缺失值。
您还有另一个问题,即在您引用的两个函数中ind[[i]],我认为这意味着在某些时候此代码是循环的一部分。我的猜测是所有引用都ind[[i]]应该是x.
| 归档时间: |
|
| 查看次数: |
43301 次 |
| 最近记录: |