【问题标题】:How to change a latitude (rows) x longitude (columns) data frame into a latitude (column 1), longitude (column 2), value (column 3) data frame in R?如何将纬度(行)x经度(列)数据框更改为R中的纬度(列1),经度(列2),值(列3)数据框?
【发布时间】:2023-03-31 17:56:01
【问题描述】:

我有一个数据框,其中纬度 (lat) 值是行的名称,经度 (lon) 值是列的名称,数据框的每个单元格的温度 (temp) 值为对我感兴趣(或 NA 值),例如:

    lon  lon  lon  lon  lon  lon
lat temp temp temp temp temp temp
lat temp temp temp temp temp temp
lat temp temp temp temp temp temp
lat temp temp temp temp temp temp

我的问题是,我怎样才能重新格式化这个数据框,使其格式为:

    C1    C2    C3
R1  lat  lon   temp
R2  lat  lon   temp
R3  lat  lon   temp
R4  lat  lon   temp

非常感谢任何帮助、功能或示例代码!

【问题讨论】:

    标签: r dataframe multiple-columns rows reformatting


    【解决方案1】:

    我们可能会使用

    as.data.frame(as.table(m1))
    

    或使用melt 来自reshape2

    library(reshape2)
    melt(m1)
    

    【讨论】:

      【解决方案2】:

      我们可以使用来自tidyrpivot_longer。这是一个模拟数据的例子:

      df <- structure(list(lon1 = c(1L, 1L, 1L, 1L), lon2 = c(2L, 2L, 2L, 
      2L), lon3 = c(3L, 3L, 3L, 3L), lon4 = c(3L, 3L, 3L, 3L), lon5 = c(4L, 
      4L, 4L, 4L), lon6 = c(5L, 5L, 5L, 5L)), row.names = c("lat1", 
      "lat2", "lat3", "lat4"), class = "data.frame")
      
      library(dplyr)
      library(tidyr)
      df %>% 
        rownames_to_column("latitude") %>% 
        pivot_longer(
          cols = -latitude,
            names_to="longitude",
            values_to= "temperature"
          )
      

      输出:

         latitude longitude temperature
         <chr>    <chr>           <int>
       1 lat1     lon1                1
       2 lat1     lon2                2
       3 lat1     lon3                3
       4 lat1     lon4                3
       5 lat1     lon5                4
       6 lat1     lon6                5
       7 lat2     lon1                1
       8 lat2     lon2                2
       9 lat2     lon3                3
      10 lat2     lon4                3
      # ... with 14 more rows
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-03
        • 2022-06-13
        • 1970-01-01
        相关资源
        最近更新 更多