0

我有这个矩阵(头部和尾部在下面给出),它有美国的纬度、经度和变量,时间段从 1948 年 1 月到 2004 年 12 月:

  # head of matrix
  lon  lat  month   value
1 -124.5 31.5 1980.1    NA
2 -123.5 31.5 1980.1    NA
3 -122.5 31.5 1980.1    NA
4 -121.5 31.5 1980.1    NA
5 -120.5 31.5 1980.1    NA
6 -119.5 31.5 1980.1    NA

# tail of matrix  
           lon  lat   month   value
[129595,] -106.5 48.5 2004.12     0
[129596,] -105.5 48.5 2004.12     0
[129597,] -104.5 48.5 2004.12    71
[129598,] -103.5 48.5 2004.12    NA
[129599,] -102.5 48.5 2004.12    NA
[129600,] -101.5 48.5 2004.12    NA

我想将它重塑为一年中每个月的这种形式,例如这是 1980 年 1 月的:

lon....>    31.5       32.5       33.5    ....     48.5
lat -101.5 value11   value12     value13
 .  -102.5 ....
 .  -103.5
 .    .
 \/   .                          value ii

有什么办法可以做到吗?

4

3 回答 3

1
> dat <- read.table(text="lon  lat  month   value
+  -124.5 31.5 1980.1    2
+  -123.5 31.5 1980.1    3
+  -122.5 31.5 1980.1    4
+  -121.5 31.5 1980.1    5
+  -120.5 31.5 1980.1    6
+  -119.5 31.5 1980.1    7
+  -106.5 48.5 2004.12     0
+  -105.5 48.5 2004.12     0
+  -104.5 48.5 2004.12    71
+  -103.5 48.5 2004.12    8
+  -102.5 48.5 2004.12    9
+  -101.5 48.5 2004.12    0", header=TRUE)
> xtabs(value~lat+lon+month, data=dat, exclude="")
, , month = 1980.1

      lon
lat    -124.5 -123.5 -122.5 -121.5 -120.5 -119.5 -106.5 -105.5 -104.5 -103.5
  31.5      2      3      4      5      6      7      0      0      0      0
  48.5      0      0      0      0      0      0      0      0      0      0
      lon
lat    -102.5 -101.5
  31.5      0      0
  48.5      0      0

, , month = 2004.12

      lon
lat    -124.5 -123.5 -122.5 -121.5 -120.5 -119.5 -106.5 -105.5 -104.5 -103.5
  31.5      0      0      0      0      0      0      0      0      0      0
  48.5      0      0      0      0      0      0      0      0     71      8
      lon
lat    -102.5 -101.5
  31.5      0      0
  48.5      9      0
于 2013-10-08T20:38:12.547 回答
1

dcast在这种情况下,来自 reshape2 是你的朋友。假设您的 data.frame 被调用df

> library(reshape2)
> dcast(df, lat + month ~lon)
   lat  month -124.5 -123.5 -122.5 -121.5 -120.5 -119.5
1 31.5 1980.1     NA     NA     NA     NA     NA     NA

让我们NA用一些随机值替换,看看它是如何工作的

> set.seed(1)
> df[,4 ] <- sample(20:60, 6)
> df  # this is how the new df looks like 
     lon  lat  month value
1 -124.5 31.5 1980.1    30
2 -123.5 31.5 1980.1    34
3 -122.5 31.5 1980.1    42
4 -121.5 31.5 1980.1    54
5 -120.5 31.5 1980.1    27
6 -119.5 31.5 1980.1    52

> dcast(df, lat + month ~lon)  # here's the job done by `dcast`
   lat  month -124.5 -123.5 -122.5 -121.5 -120.5 -119.5
1 31.5 1980.1     30     34     42     54     27     52
于 2013-10-08T20:38:59.357 回答
0
library(reshape2)

dcast(mat, id.var=NULL,formula = month+lon ~ lat, value.var="value")
于 2013-10-08T20:36:31.367 回答