使用for循环计算变量,然后在R中放入数据帧

时间:2017-03-03 16:40:49

标签: r for-loop dataframe

这应该是一个简单的问题,但我仍然是编程的新手。我有一堆像这样的坐标:

> require(geosphere)  
> coordinates(locs)
Longitude Latitude
0   -119.8304 34.44190
1   -119.6768 34.41962
2   -119.7162 34.41911
3   -119.7439 34.44017
4   -120.4406 34.63925
5   -119.5296 34.40506
6   -120.4198 34.93860
7   -119.8221 34.43598
8   -119.7269 34.43728
9   -120.4252 34.96727
10  -120.4573 34.65367
11  -120.4581 34.65369

我在这些位置周围创建了缓冲区并计算了1公里内的点数,例如:

fivekm <- cbind(coordinates(locs), X=rowSums(distm (coordinates(locs)[,1:2], fun = distHaversine) / 1000 <= 5)) # number of points within 5 km

输出是:

> head(fivekm)
   Longitude Latitude  X
0   -119.8304 34.44190 14
1   -119.6768 34.41962 19
2   -119.7162 34.41911 25
3   -119.7439 34.44017 22
4   -120.4406 34.63925 12
5   -119.5296 34.40506  6

我想编写一个for循环来计算多个距离的点数,因此对值<= 5迭代{5, 1.5, 1.4, 1.3, 1.2, 1, 0.5, 0.1, 0.001}

然后我想将输出的值放在一个看起来像这样的数据框中:

   Longitude Latitude  5     1.5 etc...
0   -119.8304 34.44190 14    8
1   -119.6768 34.41962 19    5
2   -119.7162 34.41911 25    9
3   -119.7439 34.44017 22    7

谢谢!

2 个答案:

答案 0 :(得分:2)

使用lapply将允许您遍历所有边界

library(geosphere)

df1 <- data.frame(longitude=c(-119.8304, -119.6768, -119.7162, -119.7439, -120.4406, -119.5296, -120.4198, -119.8221, -119.7269, -120.4252, -120.4573, -120.4581),
                  lattitude=c(34.44, 34.42, 34.42, 34.44, 34.64, 34.41, 34.94, 34.44, 34.44, 34.97, 34.65, 34.65))

boundary <- c(5, 1.5, 1.4, 1.3, 1.2, 1, 0.5, 0.1, 0.001)
names(boundary) <- boundary

df1 <- cbind(df1, lapply(boundary, function(x) rowSums(distm(df1, fun = distHaversine) / 1000 <= x)))

> df1
   longitude lattitude 5 1.5 1.4 1.3 1.2 1 0.5 0.1 0.001
1  -119.8304     34.44 2   2   2   2   2 2   1   1     1
2  -119.6768     34.42 2   1   1   1   1 1   1   1     1
3  -119.7162     34.42 4   1   1   1   1 1   1   1     1
4  -119.7439     34.44 3   1   1   1   1 1   1   1     1
5  -120.4406     34.64 3   1   1   1   1 1   1   1     1
6  -119.5296     34.41 1   1   1   1   1 1   1   1     1
7  -120.4198     34.94 2   1   1   1   1 1   1   1     1
8  -119.8221     34.44 2   2   2   2   2 2   1   1     1
9  -119.7269     34.44 3   1   1   1   1 1   1   1     1
10 -120.4252     34.97 2   1   1   1   1 1   1   1     1
11 -120.4573     34.65 3   2   2   2   2 2   2   2     1
12 -120.4581     34.65 3   2   2   2   2 2   2   2     1

答案 1 :(得分:1)

您应该指定使用geosphere包中的函数。我创建了一个df对象来创建数据,以便我可以重现该问题,但只使用前3行。

df <- data.frame(Long = c(-119.8304, -119.6768, -119.7162), Lat = c(34.44190, 34.41962, 34.41911))
dist <- c(5, 1.5, 1.4, 1.3, 1.2, 1, 0.5, 0.1, 0.001)
result <- matrix(nrow = nrow(df), ncol = length(dist))
for (i in seq_along(dist)){
result[,i] <- rowSums(distm(coordinates(df)[,1:2]) / 1000 <= i)
}