使用rast(...,type=xyz)将数据.frame转换为terra包中的SpatRaster时指定图层(R)

7eumitmz  于 2022-12-30  发布在  其他
关注(0)|答案(2)|浏览(163)

我有一个包含lon/lat/time/values列的简单csv文件:

df <- data.frame(longitude=rep(c(10.5,11,12),10),
  latitude=rep(c(10.5,11,12),10),
  date= as.Date(rep(c("2012-01-01", "2012-02-01", "2012-03-01"), 10)),
  vals=rnorm(30,10,5))

我想把这个转换成一个SpatRaster使用S4方法的签名'data.frame' rast(x, type="xyz", crs="", digits=6, extent=NULL),其中每个“日期”将是一个单独的层。
导入时不带日期也可以正常工作:

df.subset <- select(df,-date) 

tmp <- terra::rast(df.subset, type="xyz")

我尝试按日期拆分SpatRaster,但得到Error in .local(x, f, ...) : length(f) == nlyr(x) is not TRUE错误:

split(tmp, as.factor(df$date))

我可以想到一种循环方法
1.按日期拆分df:split(df, c("2012-01-01", "2012-02-01", "2012-03-01"))
1.为每个日期创建单独的散射栅格
1.使用merge将单个SpatRasters与命名图层合并
在terra中有没有更整洁的方法来做这件事?

fnx2tebb

fnx2tebb1#

可以使用apply函数之一创建栅格列表,然后在此列表中再次使用rast

library(terra)
library(dplyr)
    
# I changed the data so that different dates have many locations 
# rast complains otherwise
df <- data.frame(longitude=rep(c(10.5,11,12),10),
                                 latitude=rep(c(10.5,11,12),10),
                                 date= as.Date(c(rep("2012-01-01", 10), rep("2012-02-01", 10), rep("2012-03-01", 10))),
                                     vals=rnorm(30,10,5))
    
# A function to filter for dates 
# and remove the date column (change this if you want to keep it)
myrast <- function(df, date_to_filter) {
    df1 <- df %>% filter(date == date_to_filter) %>% select(-date)
    raster_return <- rast(x = df1, type='xyz')
    raster_return
}
    
# Iterate over all the unique dates
rr <- sapply(unique(df$date), function(d) myrast(df, d))
    
# Combine the list of raster objects
rr_all <- rast(rr)

plot(rr_all)

06odsfpq

06odsfpq2#

以下是使用splitreshape的方法
示例数据

library(terra)
set.seed(0)
df <- data.frame(longitude=rep(seq(10,19,1), 3),
  latitude=rep(seq(10, 19,1), 3),
  date= as.Date(rep(c("2012-01-01", "2012-02-01", "2012-03-01"), each=10)),
  vals=rnorm(30,10,5))

再成形

w <- reshape(df, timevar="date", idvar=c("longitude", "latitude"), direction="wide")
x <- rast(w, type="xyz")

分裂

r <- split(df[,-3], df$date)
r <- lapply(r, \(i) rast(i, type="xyz")) 
r <- rast(r)

# and perhaps
time(r) <- as.Date(names(r))

r
#class       : SpatRaster 
#dimensions  : 10, 10, 3  (nrow, ncol, nlyr)
#resolution  : 1, 1  (x, y)
#extent      : 9.5, 19.5, 9.5, 19.5  (xmin, xmax, ymin, ymax)
#coord. ref. :  
#source(s)   : memory
#names       : 2012-01-01, 2012-02-01, 2012-03-01 
#min values  :    2.30025,   3.812308,   3.577003 
#max values  :   22.02327,  13.817967,  15.428847 
time (days)  : 2012-01-01 to 2012-03-01

您也可以在lapply循环中"手动"执行拆分

ud <- unique(df$date)
x <- lapply(ud, \(d) rast(df[df$date == d, -3], type="xyz"))
x <- rast(x)
names(x) <- ud

相关问题