我有纬度和经度数据,例如......
lat=runif(1000, min = 22.1, max = 22.8)
lon=runif(1000, min = 120, max = 120.6)
latlon=cbind(lat,lon)
我想基于此将它们分类到不同的区域......
Zone=c("A","B","C","C","C","D","E","E","E")
North=c(23,23,22.83,22.67,22.42,22.33,22.33,22.42,22.50)
South=c(22.67,22.67,22.67,22.33,22.33,22.08,22.08,22.33,22.42)
East=c(120,120.2,120.2,120.3,120.4,120.5,120.7,120.6,120.5)
West=c(119.7,120,120.2,120,120.3,120.2,120.5,120.4,120.3)
data.frame(cbind(Zone,North,South,East,West))
我想将我的gis数据latlon
分成5个不同的区域(A,B,C,D,E)
之前我曾尝试使用ifelse
,但似乎效率不高
无论如何,我可以更快地完成它?
===================== 我根据Adrian Martin的建议编写了一个新代码
newzone=case_when(lat >= zzz$South[1] & lat <= zzz$North[1] & lon <= zzz$East[1] & lon >= zzz$West[1]~ zzz$Zone[1],
lat >= zzz$South[2] & lat <= zzz$North[2] & lon <= zzz$East[2] & lon >= zzz$West[2]~ zzz$Zone[2],
lat >= zzz$South[3] & lat <= zzz$North[3] & lon <= zzz$East[3] & lon >= zzz$West[3]~ zzz$Zone[3],
lat >= zzz$South[4] & lat <= zzz$North[4] & lon <= zzz$East[4] & lon >= zzz$West[4]~ zzz$Zone[4],
lat >= zzz$South[5] & lat <= zzz$North[5] & lon <= zzz$East[5] & lon >= zzz$West[5]~ zzz$Zone[5],
lat >= zzz$South[6] & lat <= zzz$North[6] & lon <= zzz$East[6] & lon >= zzz$West[6]~ zzz$Zone[6],
lat >= zzz$South[7] & lat <= zzz$North[7] & lon <= zzz$East[7] & lon >= zzz$West[7]~ zzz$Zone[7],
lat >= zzz$South[8] & lat <= zzz$North[8] & lon <= zzz$East[8] & lon >= zzz$West[8]~ zzz$Zone[8],
lat >= zzz$South[9] & lat <= zzz$North[9] & lon <= zzz$East[9] & lon >= zzz$West[9]~ zzz$Zone[9])
无论如何我可以让代码更简单吗?感谢
答案 0 :(得分:0)
cut()(与r2evans&#39;评论相关联的答案)如果您正在切割成相等宽度的5个部分或其他任何内容,或者如果您有一些比例矢量,那么您将会尝试匹配。如果你试图匹配已经存在的lat / lon坐标(因为你可能会尝试使用ifelse),我会使用dplyr的函数case_when()。
library(dplyr)
latlon <- bind_cols(lat, lon) %>%
mutate(Zone = case_when(.$lat > 22.83 & .$lon > 120.2 ~ A,
.$lat > 22.42 & .$lon > 120.0 ~ B,
etc etc)
case_when是如何将ifelse-type语句转换为dplyr链。我相信它会更快地发挥作用。