这个代码报错了 > for (i in seq_along(times)) { + new_r[[i]] <- r[] + } Error in new_r[[i]] <- r[] : more elements supplied than there are to replace
时间: 2023-12-12 15:04:10 浏览: 37
这个错误可能是由于 `new_r` 和 `r` 的行列数不匹配,导致在对 `new_r` 赋值时出现了维度不匹配的错误。你可以尝试在每次循环前,使用 `print(dim(new_r))` 和 `print(dim(r))` 分别打印 `new_r` 和 `r` 的行列数,查看是否一致。
另外,如果你的 `r` 是多波段数据,那么你需要使用 `r[[1]]` 获取第一波段的值,而不是 `r[]`。
相关问题
出现了报错> for (i in seq_along(times)) { + print(dim(new_r)) + print(dim(r)) + new_r[[i]] <- r[[1]] + } [1] 125 265 1 [1] 125 265 1 [1] 125 265 1 [1] 125 265 1 [1] 125 265 1 [1] 125 265 1 Error in .local(x, i, j = j, ..., value) : index should be <= nlayers(x)+1
这个错误是由于 `new_r` 的第三个维度超过了 `r` 的第三个维度,导致在对 `new_r` 赋值时出现了维度不匹配的错误。你可以使用 `dropLayer()` 函数将 `r` 的多余维度去掉,使其和 `new_r` 的维度一致。
以下是修改后的代码:
```
library(raster)
# 输入路径
in_path <- "E:/LAI/GLASS_LAI/IWEMS_LAI/8118x/"
# 输出路径
out_path <- "E:/LAI/GLASS_LAI/IWEMS_LAI/8118s/"
# 读取第一天的tif文件,并去掉多余的维度
r <- dropLayer(raster(paste0(in_path, "/19810101.tif")))
# 新建一个空白矩阵
new_r <- raster(nrow = nrow(r), ncol = ncol(r), xmn = extent(r)[1], xmx = extent(r)[2], ymn = extent(r)[3], ymx = extent(r)[4], crs = proj4string(r))
# 获取每小时的时间戳
times <- seq(as.POSIXct('2022-01-01 00:00:00'), as.POSIXct('2022-01-09 23:00:00'), by = 'hour')
# 将每小时的值设置为第一天的值
for (i in seq_along(times)) {
print(dim(new_r))
print(dim(r))
new_r[[i]] <- r
}
# 设置时间属性
names(new_r) <- format(times, "%Y-%m-%d %H:%M:%S")
# 导出为tif文件
writeRaster(new_r, filename = paste0(out_path, "/hourly_data.tif"), format = "GTiff", overwrite = TRUE)
```
在读取第一天的tif文件时,使用 `dropLayer()` 函数去掉多余的维度。
在循环中,将 `r[[1]]` 替换为 `r`,这样 `r` 的维度就和 `new_r` 一致了。
> for (i in seq_along(k_values)) { + k <- k_values[i] + clusters <- cutree(hclust_result, k = k) + ch_score <- cluster.stats(dist_matrix, clusters)["ch"] + ch_scores[i] <- ch_score + } Error in sc$clus.avg.widths : $ operator is invalid for atomic vectors
在你的代码中,你使用了 `sc$clus.avg.widths`,但是出现了错误 `Error in sc$clus.avg.widths : $ operator is invalid for atomic vectors`。这个错误是由于 `sc` 是一个原子向量,而不是一个列表或数据框。
要解决这个问题,你可以尝试检查 `sc` 对象的类型,确保它是一个列表或数据框,并且包含了你想要访问的属性。你可以使用 `str(sc)` 函数来查看 `sc` 对象的结构和属性。
如果 `sc` 是一个原子向量,并且你确实需要访问其中的属性,你可以尝试使用其他适当的方法或函数来获取所需的属性。具体的解决方法可能取决于你的代码和数据结构。
请记住,我只能根据你提供的信息做出推测。如果你能提供更多的代码和上下文信息,我可以更具体地帮助你解决这个问题。