【问题标题】:Converting coordinate ASC file (raster data) into a XY coordinate data frame将坐标 ASC 文件(栅格数据)转换为 XY 坐标数据框
【发布时间】:2018-06-18 10:02:46
【问题描述】:

我已经读入了一个 ASCII 文件,其值对应于英国坐标网格,但是,如果我想应用 which.closest() 命令,我需要能够根据 X 和 Y 坐标指定列.所以现在,下面是我拥有的数据框类型的随机示例摘录:

           1000 2000 3000 4000 5000
    66000     1    2    3    4    5
    65000     1    2    3    4    5
    64000     1    2    3    4    5
    63000     1    2    3    4    5
    62000     1    2    3    4    5

这是脚本,因此您可以复制此摘录:

    a=c(1,1,1,1,1)
    b=c(2,2,2,2,2)
    c=c(3,3,3,3,3)
    d=c(4,4,4,4,4)
    e=c(5,5,5,5,5)
    df=data.frame(a,b,c,d,e)
    colnames_df=seq(1000,5000,1000)
    rownames_df=seq(62000,66000,1000)
    rownames_df=rev(rownames_df)
    colnames(df)=colnames_df
    rownames(df)=rownames_df
    df

这是我希望能够继续分析的数据框:

    X     Y      Z
    1000  62000  1
    1000  63000  1
    3000  64000  1
    1000  65000  1
    1000  66000  1
    2000  62000  2
    2000  63000  2
    2000  64000  2
    2000  65000  2
    2000  66000  2 
    ...(etc.)

是否有代码可以轻松完成此操作,而不是手动设置新数据框、指定列和行等,因为我有一个 1377 x 812 的数据框,用于 20 种不同的空气质量化学测量,所以如果有一个代码,它会让我的生活更轻松。任何帮助表示赞赏!谢谢!

【问题讨论】:

    标签: r ascii raster coordinate


    【解决方案1】:

    如果我理解正确的话:

    library(dplyr)
    library(tidyr)
    df <- cbind(Y = rownames(df), df)
    rownames(df) <- NULL
    df <- df %>% gather(X, Z, -Y)
    

    【讨论】:

      【解决方案2】:

      这里有两种更传统的方法(与 Thor6 建议的 gather 相比):

      X <- as.integer(rep(colnames(df), each=nrow(df)))
      Y <- as.integer(rep(rownames(df), nrow(df)))
      a <- cbind(X, Y, Z = as.vector(as.matrix(df)))
      

      reshape(相当复杂)

      cn <- colnames(df)
      b <- reshape(df, direction='long', varying=cn, v.names = "Z", times=cn, timevar = "X" )
      b$Y <- rownames(df)
      b <- b[, c('X', 'Y', 'Z')]
      rownames(b) <- NULL
      

      但是,鉴于这些是栅格数据,如果它们以标准文件格式存储,则无需首先制作 data.frame,您可以执行以下操作:

      library(raster)
      r <- raster('raster data file')
      d <- rasterToPoints(r) 
      

      如果你还想要NA的单元格

      e <- cbind(xyFromCell(r, 1:ncell(r)), Z=values(r))
      

      工作示例

      f <- system.file("external/test.grd", package="raster")
      r <- raster(f)
      d <- rasterToPoints(r) 
      e <- cbind(xyFromCell(r, 1:ncell(r)), Z=values(r))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多