How to switch rows in R?

三世轮回 提交于 2019-12-11 13:19:48

问题


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).

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

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...


回答1:


You can change the order of the factor levels:

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



回答2:


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.



来源:https://stackoverflow.com/questions/18976078/how-to-switch-rows-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!