如何在R中切換行?

[英]How to switch rows in R?


I have a array with following content:

我有一個包含以下內容的數組:

> head(MEAN)
1901DJF     1901JJA     1901MAM     1901SON     1902DJF     1902JJA 
-0.45451556 -0.72922229 -0.17669396 -1.12095590 -0.86523850 -0.04031273 

This should be a time series with seasonal mean values from 1901 to 2009. The problem is that the generated column heads are strictly alphabetically ordered. However, in terms of season this doesn't make to much sense, e.g. JJA (june, july, august) is leading MAM (march, april, may).

這應該是具有1901年至2009年季節性平均值的時間序列。問題是生成的列頭嚴格按字母順序排列。然而,就季節而言,這並沒有多大意義,例如: JJA(7月,7月,8月)領導MAM(3月,4月,5月)。

How could I switch each MAM and JJA entry of the array?

我怎么能切換陣列的每個MAM和JJA條目?

PS: MEAN is generated applying tapply on the data.frame pdsi

PS:MEAN是在data.frame pdsi上應用tapply生成的

> head(pdsi)
    date      scPDSI month seas seasyear
1 1901-01-01 -0.10881074   Jan  DJF  1901DJF
2 1901-02-01 -0.22287750   Feb  DJF  1901DJF
3 1901-03-01 -0.12233192   Mär  MAM  1901MAM
4 1901-04-01 -0.04440915   Apr  MAM  1901MAM
5 1901-05-01 -0.36334082   Mai  MAM  1901MAM
6 1901-06-01 -0.52079030   Jun  JJA  1901JJA
>
> MEAN <- tapply(pdsi$scPDSI, ts.pdsi$seasyear, mean, na.rm = T)

May be there is also known a more elegant way to calculate seasonal means...

可能還有一種更為優雅的季節性計算方法...

2 个解决方案

#1


1  

You can change the order of the factor levels:

您可以更改因子級別的順序:

pdsi[["seasyear"]] = factor(pdsi[["seasyear"]], levels = c("1901DJF", "1901MAM", etc))

#2


0  

I think this is a fairly simple way of re-ordering your means, however, it does have the assumption that your data is already ordered chronologically in the data set. So if that holds this should work.

我認為這是重新排序方法的一種相當簡單的方法,但是,它確實假設您的數據已按時間順序排列在數據集中。所以,如果這有,這應該工作。

I also created some random data, rather than copying your data, but the results should be the same

我還創建了一些隨機數據,而不是復制數據,但結果應該是相同的

seasons = c("1901DJF", "1901MAM", "1901JJA")
seasons = rep(seasons, c(2, 3, 1))
data = data.frame(runif(1:6), seasons)

MEAN = tapply(data[,1], data[,2], mean)

  1901DJF   1901JJA   1901MAM 
0.5799779 0.3724785 0.6514327 

order = unique(seasons)
MEAN[order]

 1901DJF   1901MAM   1901JJA 
0.5799779 0.6514327 0.3724785 

What this does is take the order of seasyear in the data set, and reorders the object MEAN to reflect that order. Again, it assumes your data is chronologically ordered in the raw file, but I think this is a safe assumption. Apologies if it is not the case.

這樣做是在數據集中采用seasyear的順序,並重新排序對象MEAN以反映該順序。同樣,它假設您的數據在原始文件中按時間順序排序,但我認為這是一個安全的假設。如果不是這樣,請道歉。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/09/24/72a136b4d83a9ab32702dc958cabb02d.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com