gpt4 book ai didi

R:在函数中需要有限的 'ylim'值

转载 作者:行者123 更新时间:2023-12-04 11:59:02 24 4
gpt4 key购买 nike

我想为data.frame xy中的每个组(由ID定义)绘制数据。如果在1946年之前的一年中,应该执行plot 2。当年份介于1946年至2014年之间时,应执行plot1

我的问题:在没有NA值的情况下,它可以正常工作,但是由于我有数据缺口,我依靠NA来定义这些数据缺口。这就是为什么我得到一个错误:error in plot.window(need finite 'ylim' values)的原因。我试图将finite=T放在y轴的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)))

最佳答案

plot1中,将y = range(x$VALUE)更改为y = range(x$VALUE, na.rm=TRUE)以删除NA缺少的值。

您还有另一个问题,即在两个函数中都引用了ind[[i]],我认为这意味着在某些时候该代码是循环的一部分。我的猜测是对ind[[i]]的所有引用都应该是x

关于R:在函数中需要有限的 'ylim'值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25871292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com