在 R 中,我尝试使用 sf 包中的 st_point() 创建点。
我的输入是一个 data.frame,其中一列是 x 坐标,另一列是 y 坐标:
# Code to generate input
library(sf)
N <- 10
df <- data.frame(x=rnorm(N),y=rnorm(N))
Run Code Online (Sandbox Code Playgroud)
我想做的只是
# Code to generate examplar output
L <- list()
for (i in 1:N)
{
L[[i]] <- st_point(c(df$x[i],df$y[i]))
}
st_sfc(L)
Run Code Online (Sandbox Code Playgroud)
但我尝试用 mapply(.) 来代替循环
mapply(function(x,y) sum(c(x,y)),df$x,df$y)
mapply(function(x,y) st_point(c(x,y)),df$x,df$y)
Run Code Online (Sandbox Code Playgroud)
它适用于添加列,但不适用于创建空间点。
我的问题有两个:(1)为什么使用 mapply 会失败?(2) 有效的方法是什么?
如果您阅读文档,?mapply您会发现默认情况下它会简化结果并在这种情况下返回一个矩阵。你可以告诉它不要简化。
# Code to generate input
library(sf)
N <- 10
df <- data.frame(x=rnorm(N),y=rnorm(N))
test <- mapply(function(x,y) st_point(c(x,y)),df$x,df$y)
str(test)
# num [1:2, 1:10] -1.42485 0.00776 -0.78035 -0.03221 0.30925 ...
test <- mapply(function(x,y) st_point(c(x,y)),df$x,df$y,SIMPLIFY = FALSE)
str(test)
# List of 10
# $ : 'XY' num [1:2] -1.42485 0.00776
# $ : 'XY' num [1:2] -0.7804 -0.0322
# $ : 'XY' num [1:2] 0.309 -0.541
# $ : 'XY' num [1:2] 0.459 -0.614
# $ : 'XY' num [1:2] -2.919 -0.169
# $ : 'XY' num [1:2] 0.689 0.168
# $ : 'XY' num [1:2] -1.066 0.711
# $ : 'XY' num [1:2] 1.09 0.925
# $ : 'XY' num [1:2] 0.756 0.81
# $ : 'XY' num [1:2] -1.17 -2.13
Run Code Online (Sandbox Code Playgroud)
如果您无论如何都要在数据框中存储内容,您可以考虑dplyr执行此操作的方法。但是,您需要将这些点包装在 list() 中才能使 dplyr 变异发挥作用。
library(dplyr)
test <- df %>%
rowwise() %>%
mutate(point = list(st_point(c(x,y))))
str(test$point)
# List of 10
# $ : 'XY' num [1:2] -1.42485 0.00776
# $ : 'XY' num [1:2] -0.7804 -0.0322
# $ : 'XY' num [1:2] 0.309 -0.541
# $ : 'XY' num [1:2] 0.459 -0.614
# $ : 'XY' num [1:2] -2.919 -0.169
# $ : 'XY' num [1:2] 0.689 0.168
# $ : 'XY' num [1:2] -1.066 0.711
# $ : 'XY' num [1:2] 1.09 0.925
# $ : 'XY' num [1:2] 0.756 0.81
# $ : 'XY' num [1:2] -1.17 -2.13
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2868 次 |
| 最近记录: |