如何在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
这应该是一个时间序列,具有从 1901 年到 2009 年的季节性平均值.问题是生成的列标题是严格按字母顺序排列的.但是,就季节而言,这没有多大意义,例如JJA(6 月、7 月、8 月)领先 MAM(3 月、4 月、5 月).
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).
如何切换数组的每个 MAM 和 JJA 条目?
How could I switch each MAM and JJA entry of the array?
PS:MEAN 是在 data.frame pdsi 上应用 tapply 生成的
PS: MEAN is generated applying tapply on the data.frame pdsi
> 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...
推荐答案
您可以更改因子水平的顺序:
You can change the order of the factor levels:
pdsi[["seasyear"]] = factor(pdsi[["seasyear"]], levels = c("1901DJF", "1901MAM", etc))
这篇关于如何在R中切换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!