gpt4 book ai didi

r - 考虑键列之间的范围匹配,合并两个数据框

转载 作者:行者123 更新时间:2023-12-04 12:31:41 25 4
gpt4 key购买 nike

我是 R 编程的初学者。我目前正在尝试从包含 X 和 Y 坐标和站点名称的数据框中检索一些站点名称,并将它们复制到具有特定点的不同数据框中。

    FD <- matrix(data =c(rep(1, 500), rep(0, 500),
rnorm(1000, mean = 550000, sd=4000),
rnorm(1000, mean = 6350000, sd=20000), rep(NA, 1000)),
ncol = 4, nrow = 1000, byrow = FALSE)
colnames(FD) <- c('Survival', 'X', 'Y', 'Site')
FD <- as.data.frame(FD)

shpxt <- matrix(c(526654.7,526810.5 ,6309098,6309187,530405.4,530692,
6337699, 6338056,580432.7, 580541.9, 6380246,6380391,
585761.3, 585847.6, 6379665, 6379759, 584192.1, 584279.4,
6382358, 6382710, 583421.2, 583492.4, 6379356, 6379425,
532395.5, 532515.3 , 6336421, 6336587, 534694.6, 534791.2,
6335620, 6335740, 536749.8, 536957.5, 6337584, 6338130, 590049.6,
590419.4, 6372232, 6372432, 580443, 580756.5, 6386342, 6386473,
575263.9, 575413.7, 6380416, 6380530, 584625.1, 584753.9, 6381009,
6381335), ncol = 4, nrow = 13, byrow = TRUE)
sites <- c("Brandbaeltet", "Brusaa", "Granly", "Jerup Strand", "Knasborgvej",
"Milrimvej", "Overklitten", "Oversigtsareal", "Sandmosen",
"Strandby", "Troldkaer", "Vaagholt", "Videsletengen")
colnames(shpxt) <- c("Xmin", "Xmax", "Ymin", "Ymax")
shpxt <- as.data.frame(shpxt)
shpxt["Sites"] <- sites

我的方法是使用这样的嵌套 for 循环:

    tester <- function(FD, shpxt)
{ for (i in 1:nrow(FD)) for (j in 1:nrow(shpxt)) # Open Function
{ if (FD[i,2] >= shpxt[j,1] | FD[i,2] <= shpxt[j,2] & # Open Loop
FD[i,3] >= shpxt[j,3] | FD[i,3] <= shpxt[j,4])
{ # Open Consequent
FD[i,4]=shpxt[j,5]
{break}
} else # Close Consequent
{FD[i,4] <- NA # Open alternative
} # Close alternative
} # Close loop
} # Close function

tester(FD, shpxt)

本质上我想搜索FD中的X和Y坐标落在哪个站点范围内,并将站点名称复制到第i行的FD$Site中。当我在我的真实数据上运行循环时,我收到以下错误消息:

test(FD, shpxt)
Error in if (FD[i, 2] >= shpxt[j, 1] | FD[i, 2] <= shpxt[j, 2] & FD[i, :
missing value where TRUE/FALSE needed

我如何让循环从此处转到循环将所需站点名称复制到我的 FD 的位置?

亲切的问候Thøger

最佳答案

考虑到键列之间的范围匹配,您想合并两个数据框。这里有两个解决方案。

使用sqldf

library(sqldf)

output <- sqldf("select * from FD left join shpxt
on (FD.X >= shpxt.Xmin and FD.X <= shpxt.Xmax and
FD.Y >= shpxt.Ymin and FD.Y <= shpxt.Ymax ) ")

使用data.table

library(data.table)

# convert your datasets in data.table
setDT(FD)
setDT(shpxt)

output <- FD[shpxt, on = .(X >= Xmin , X <= Xmax, # indicate x range
Y >= Ymin , Y <= Ymax), nomatch = NA, # indicate y range
.(Survival, X, Y, Xmin, Xmax, Ymin, Ymax, Sites )] # indicate columns in the output

有不同的替代方案可以解决这个问题,您会在其他 SO 问题中找到它 herehere .

附言。请记住,for 循环 不一定是最佳解决方案。

关于r - 考虑键列之间的范围匹配,合并两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37158839/

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