简体   繁体   English

在R中将SF包中的函数应用于每一行

[英]Apply function from sf package to each row while in R

I'm working with the sf package in R, and for that purpose I'm trying to use one of their functions to create lines. 我正在使用R中的sf包,为此,我尝试使用其功能之一来创建行。 The goal is to apply their functions to each row (columns 4:3 and 6:5) from the example data frame below. 目标是将它们的功能应用于以下示例数据框中的每一行(列4:3和6:5)。

df <- read.table(text = " from to from_lat from_lon to_lat to_lon travel_time
1  8015345 8849023 50.77083 6.105277 50.71896 6.041269    7.000000
2  8200100 8200101 49.60000 6.133333 49.63390 6.136765    8.000000
3  8200100 8200110 49.60000 6.133333 49.74889 6.106111   16.000000
4  8200100 8200510 49.60000 6.133333 49.61111 6.050000    4.857143
5  8200100 8200940 49.60000 6.133333 49.55129 5.845025   28.236842
6  8200100 8866001 49.60000 6.133333 49.68053 5.809972   37.000000
7  8200100 8869054 49.60000 6.133333 49.64396 5.904150   14.000000
8  8200101 8200100 49.63390 6.136765 49.60000 6.133333    7.000000
9  8200101 8200110 49.63390 6.136765 49.74889 6.106111   11.000000
10 8200110 8200100 49.74889 6.106111 49.60000 6.133333   17.074074", header = TRUE)

I know how to do this for one row: 我知道如何做到这一点:

library(sf)
library(dplyr)

x = matrix(as.numeric(c(df[1, c(4, 3)],
             df[1, c(6, 5)])), ncol = 2, byrow = TRUE)
class(x)
typeof(x)
l1 = st_linestring(x = x)
lsf = l1 %>% 
  st_sfc() %>% 
  st_sf(crs = 4326)
plot(lsf) #just to confirm that it is a line

But what I really need is to do it for every row. 但是我真正需要的是每一行都要做。 I tried to use a for loop but for some reason it messes up with the sf package classes. 我尝试使用for循环,但由于某种原因,它与sf包类弄混了。 So I would assume that the solution would involve apply() but I'm not sure how to. 因此,我认为该解决方案将涉及apply()但我不确定该如何做。

If we need to do this on each row, then we can use pmap 如果需要在每一行上执行此操作,则可以使用pmap

library(purrr)
library(dplyr)
df%>%
  select(4, 6, 3, 5) %>% 
  pmap(~ c(...) %>% 
            matrix(., ncol = 2) %>% 
            st_linestring %>%
            st_sfc %>%
            st_sf(crc = 4326))

You could use dplyr::rowwise() to do the row grouping. 您可以使用dplyr::rowwise()进行行分组。

df %>% rowwise() %>%
  mutate(line_sf = list(matrix(c(from_lon, to_lon, from_lat, to_lat), ncol = 2) %>%
           st_linestring()) ) %>%
   with(st_sfc(line_sf, crs = 4326)) %>%
   plot()

I re-arranged the last line (before plot ) to collapse the 10 line observations into a single geometry set for plotting here, but you could just leave them as individuals. 我重新布置了最后一条线(在plot之前),将10条线的观察值折叠为一个单独的几何图形集,以便在此处进行绘制,但是您可以将它们留为个人。

在此处输入图片说明

A solution that doesn't require dplyr: 不需要dplyr的解决方案:

lsf <- mapply(function(a, b, c, d) {
  list(matrix(c(a, b, c, d), ncol = 2) %>%
    st_linestring())
  }, df$from_lon, df$to_lon, df$from_lat, df$to_lat) %>%
  st_sfc(crs = 4326)

plot(lsf)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM