我的数据框包含Name
,longitude
和latitude
列。我想要一个遍历每一行的函数,从栅格堆栈中提取值并根据Name
列编写csv文件。
Name Lon Lat
Name1 11.11 47.87
Name2 150.1 -40.4
Name3 -50.2 -3.5
Name4 -100.3 49.8
library(raster)
s <- stack(replicate(5, {raster(matrix(runif(2160*4320), 2160),
xmn=-180, xmx=180, ymn=-90, ymx=90)}))
I can do that one by one:
location <- data.frame(11.11, 47.87)
ex <- extract(s, location)
write.csv(ex, "Name1.csv")
答案 0 :(得分:3)
一种非常传统的方法适用于for-loop
d1 <-c("Name1", "Name2","Name3", "Name4")
d2 <- c(11.11,150.1,-50.2,-100.3)
d3 <-c(47.87, -40.4, -3.5, 49.8)
data.df <-data.frame(d1,d2,d3)
for(i in 1:nrow(data.df))
{
location <- data.frame(data.df[i,2],data.df[,3])
ex <- extract(s, location)
fn1<-paste0(data.df[i,1],".csv")
write.csv(ex, fn1)
}
生成四个包含以下信息的文件:
"","layer.1","layer.2","layer.3","layer.4","layer.5"
"1",0.471816286211833,0.115963410818949,0.399704266572371,0.464667820138857,0.820669727399945
"2",0.616754011251032,0.354018000885844,0.602565947687253,0.86519843316637,0.660861984360963
"3",0.0691961287520826,0.128835600335151,0.199198298621923,0.968016018159688,0.597145217470825
我希望这是您正在寻找的结果。
可能有一些更先进和更好的方法(基于apply
- 家庭???)和作为R初学者也感兴趣。
答案 1 :(得分:3)
申请:
library(raster)
s <- stack(replicate(5, {raster(matrix(runif(2160*4320), 2160),
xmn=-180, xmx=180, ymn=-90, ymx=90)}))
d1 <-c("Name1", "Name2","Name3", "Name4")
d2 <- c(11.11,150.1,-50.2,-100.3)
d3 <-c(47.87, -40.4, -3.5, 49.8)
data.df <- data.frame("Name" = d1, "Lon" = d2, "Lat" = d3)
apply(X = data.df, 1, function(x, s) {
location <- as.numeric(c(x[2], x[3]))
ex <- extract(s, location)
write.csv(ex, paste0(x[1], ".csv"))
}, s = s)
请注意,如果要在函数内部使用,则必须将s对象作为函数的附加参数传递。