转换为数据框列表上的坐标

Convert to coordinates over a list of data frames

我正在尝试使用 sp 包将点值转换为坐标,以执行类似于 this question 的操作。我有一个数据框列表(完整数据集中有数百个,这里有 2 个较短的)。

> dput(df)
list(structure(list(group = c(22, 43, 43, 36, 9, 20, 35, 18, 
32, 2), mean_x_m = c(-2578373.61904762, -2082265, -1853701.875, 
-2615961.89189189, -1538829.07815509, -1753235.6200847, -1690679.5, 
-1694763.64583333, -1700343.15217391, -1416060), mean_y_m = c(3242738.76190476, 
2563892.5, 1945883.125, 3130074.86486486, 1373724.65001039, 1468737.97186933, 
2123413.5, 1442167.01388889, 2144261.73913043, 1352573.33333333
)), .Names = c("group", "mean_x_m", "mean_y_m"), row.names = c(72L, 
140L, 142L, 121L, 27L, 66L, 114L, 60L, 105L, 5L), class = "data.frame"), 
    structure(list(group = c(12, 12, 47, 30, 39, 34, 47, 22, 
    10, 1), mean_x_m = c(-1830635.68663753, -2891058.33333333, 
    -1637448.59886202, -1974773.67400716, -1571853.24324324, 
    -2723090.33333333, -2704594.92760618, -2240863.49122807, 
    -1940748.88253242, -2176724.69924812), mean_y_m = c(2324222.49926225, 
    3261997.5, 2057096.55049787, 2411733.29933653, 1447883.78378379, 
    3406879.26666667, 3291053.77606178, 2788255.49473684, 2176919.6882151, 
    2920168.77443609)), .Names = c("group", "mean_x_m", "mean_y_m"
    ), row.names = c(67L, 68L, 243L, 155L, 202L, 173L, 244L, 
    114L, 61L, 3L), class = "data.frame"))

我可以一次拉出一个数据帧并毫无问题地转换为 SpatialPointsDataFrame。

df1 = df[[1]]
coordinates(df1) = ~mean_x_m+mean_y_m

我的问题是我无法让它使用一个函数遍历整个列表,甚至无法让该函数为单个数据帧工作。

c = function(f){coordinates(f) = ~mean_x_m+mean_y_m}
df2 = c(df1)
c(df1)
df3 = lapply(df,c)

for 循环会更好吗?我仍在学习如何使用数据框和矩阵列表,因此在此上下文中对 apply 或 for 的任何帮助将不胜感激。谢谢。

如果你的dataframes有一个一致的结构,最好把它们都放在一个dataframe中。

library(dplyr)
library(sp)

result = 
  df %>% 
  bind_rows(.id = "list_number") %>%
  as.data.frame %>%
  `coordinates<-`(~mean_x_m+mean_y_m)

如果您正在处理地理数据,我发现使用 Spatial Points 和 SpatialPointsDataFrame 类 来存储数据最简单。要转换包含具有相同列标题的数据框的列表的所有元素,您可以修改此代码:

library(sp)
# toy dataset X
X<-list(
x1 = data.frame(group =c("a","b","c"), X = c(-110.1,-110.2,-110), Y = c(44,44.2,44.3)),
x2 = data.frame(group =c("a","b","c"), X = c(-110.1,-110.2,-110), Y = c(44,44.2,44.3)))
# write a function based on the structure of your dfs 
spdf_fxn<-function(df){
SpatialPointsDataFrame(coords= cbind(df$X,df$Y), data= data.frame(group = df$group),
                     proj4string=CRS("+proj=longlat +datum=WGS84"))
}
#apply this function over the list
Out_List<-lapply(X,spdf_fxn) 

编写一个函数将通用数据帧结构转换为 SpatialPointsDataframe,并将组作为附加到每个点的数据,然后将该函数应用于列表。请注意,您必须调整列名并使用适当的 proj4string(在此示例中,它是 WGS 84 中的经度和纬度)。

您可以这样使用 lapply:

fc <- function(f){coordinates(f) = ~mean_x_m + mean_y_m; f}
lapply(df, fc)

问题是您的函数没有 return 任何东西。

制作单个对象:

 x <- lapply(1:length(df), function(i) cbind(id=i, df[[i]]))
 x <- do.call(rbind, x)
 coordinates(x) <- ~mean_x_m+mean_y_m