在保持结构的同时列出到数据帧

时间:2018-12-21 10:26:34

标签: r list dataframe matrix

str(coord_mat)
List of 1
 $ :List of 1
  ..$ : num [1:17, 1:2] -122 -122 -122 -122 -122 ...

我在coord_mat中有一个坐标对列表,我想将其转换为相同结构(第一列为lon,第二列为lat)的坐标对的数据帧(或矩阵)。

> coord_mat
[[1]]
[[1]][[1]]
           [,1]     [,2]
 [1,] -122.3435 47.63787
 [2,] -122.3435 47.63787
 [3,] -122.3434 47.63787
 [4,] -122.3434 47.63787
 [5,] -122.3434 47.63787
 [6,] -122.3434 47.63787
 [7,] -122.3434 47.63787
 [8,] -122.3434 47.63784
 [9,] -122.3433 47.63777
[10,] -122.3430 47.63772
[11,] -122.3427 47.63778
[12,] -122.3425 47.63776
[13,] -122.3423 47.63749
[14,] -122.3421 47.63718
[15,] -122.3420 47.63700
[16,] -122.3419 47.63698
[17,] -122.3419 47.63698

在R中如何保持与列表相同的双列结构?

我尝试过matrix(unlist(coord_mat)),但这只会产生一个长度为34的长向量,该向量先是lon值,然后是lat值。是因为我正在使用列表列表吗?

> matrix(unlist(coord_mat))
            [,1]
 [1,] -122.34345
 [2,] -122.34345
 [3,] -122.34340
 [4,] -122.34340
 [5,] -122.34340
 [6,] -122.34340
 [7,] -122.34340
 [8,] -122.34338
 [9,] -122.34334
[10,] -122.34299
[11,] -122.34273
[12,] -122.34249
[13,] -122.34230
[14,] -122.34208
[15,] -122.34198
[16,] -122.34194
[17,] -122.34194
[18,]   47.63787
[19,]   47.63787
[20,]   47.63787
[21,]   47.63787
[22,]   47.63787
[23,]   47.63787
[24,]   47.63787
[25,]   47.63784
[26,]   47.63777
[27,]   47.63772
[28,]   47.63778
[29,]   47.63776
[30,]   47.63749
[31,]   47.63718
[32,]   47.63700
[33,]   47.63698
[34,]   47.63698

以下是数据:

dput(coord_mat)
list(list(structure(c(-122.34345, -122.34345, -122.343398333333, 
-122.343398333333, -122.343398333333, -122.343398333333, -122.343398333333, 
-122.343376666667, -122.34334, -122.342991666667, -122.342731666667, 
-122.342491666667, -122.3423, -122.342081666667, -122.341983333333, 
-122.341943333333, -122.341943333333, 47.6378716666667, 47.6378716666667, 
47.6378683333333, 47.6378683333333, 47.6378683333333, 47.6378683333333, 
47.6378683333333, 47.637835, 47.637775, 47.6377183333333, 47.63778, 
47.63776, 47.6374916666667, 47.6371816666667, 47.6369966666667, 
47.6369783333333, 47.6369783333333), .Dim = c(17L, 2L))))

1 个答案:

答案 0 :(得分:3)

res <- coord_mat[[c(1, 1)]]
# or
res <- matrix(unlist(coord_mat), ncol = 2)
colnames(res) <- c("lon", "lat")
res
            lon      lat
 [1,] -122.3435 47.63787
 [2,] -122.3435 47.63787
 [3,] -122.3434 47.63787
 [4,] -122.3434 47.63787
 [5,] -122.3434 47.63787
 [6,] -122.3434 47.63787
 [7,] -122.3434 47.63787
 [8,] -122.3434 47.63784
 [9,] -122.3433 47.63777
[10,] -122.3430 47.63772
[11,] -122.3427 47.63778
[12,] -122.3425 47.63776
[13,] -122.3423 47.63749
[14,] -122.3421 47.63718
[15,] -122.3420 47.63700
[16,] -122.3419 47.63698
[17,] -122.3419 47.63698