【问题标题】:List to data frame while keeping structure在保持结构的同时列出数据框
【发布时间】:2019-05-21 19:48:41
【问题描述】:
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))))

【问题讨论】:

  • coord_map[[1]][[1]] 怎么样?您已经有了一个矩阵,您只需要从列表中提取它。

标签: r list dataframe matrix


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多