gpt4 book ai didi

r - 遍历数据框中的每一行,从栅格中提取值并写入 csv 文件

转载 作者:行者123 更新时间:2023-12-05 08:57:14 28 4
gpt4 key购买 nike

我有一个包含 Namelongitudelatitude 列的数据框。我想要一个遍历每一行的函数,从栅格堆栈中提取值并根据 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")

最佳答案

一种非常传统的方法是使用 for 循环

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-family???)并且作为 R 初学者我也很感兴趣。

关于r - 遍历数据框中的每一行,从栅格中提取值并写入 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34727250/

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