作为一个R新手,我认为是时候从for循环转向应用函数了。我正在为这段代码而苦苦挣扎,我想知道是否有人可以帮助我。
我有一个函数:
earth.dist <- function (long1, lat1, long2, lat2)
{
rad <- pi/180
a1 <- lat1 * rad
a2 <- long1 * rad
b1 <- lat2 * rad
b2 <- long2 * rad
dlon <- b2 - a2
dlat <- b1 - a1
a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2
c <- 2 * atan2(sqrt(a), sqrt(1 - a))
R <- 6378.145
d <- R * c
return(d)
}现在我有两个不同的数据集,一个包含预先确定的大城市列表及其经纬度坐标,另一个包含美国境内的随机位置及其经纬度坐标。我编写的for循环基本上计算随机位置的每个经度/经度坐标与预定大城市的经度/经度坐标之间的差,并将随机位置放置在最近城市所在的州。预定列表中的每个城市旁边都有一个州,该州被插入到随机城市电子表格的新列中。
有没有办法使用apply来完成这个循环?这个循环确实做到了这一点,但它又长又笨重,我知道apply函数可以做得更好。
下面是循环:
for(i in 1:nrow(randomlocations)){
vec<-vector()
for(j in 1:nrow(predeterminedcities)){
a<-earth.dist(randomlocations$long[i],randomlocations$lat[i], predeterminedcities$long[j], predeterminedcities$lat[j])
vec[[j]]<-a
}
ind<- as.numeric(which.min(vec))
randomlocations$state[i]<-as.character(predeterminedcities$STATE[ind])
print(i)
}https://stackoverflow.com/questions/38232156
复制相似问题