2

I would like to know how to keep the row names when using the running() function.

e.g. I'm applying a running correlation between two time series, and for me is very important keeping the row names because these are the Years of my time series.

This is an example:

library(gtools)

test <- matrix(rnorm(100, sd=4), nrow = 50, ncol=2, 
               dimnames= list(1966:2015, c("var1", "var2")))               

# View(running(test[,1], test[,2], fun=cor, width=5, by=5))
run.test <- running(test[,1], test[,2], fun=cor, width=5, by=5)

and I get this

    row.names   x
1   1:5 0.41739378
2   6:10    0.96117176
3   11:15   -0.54342033
4   16:20   0.09633428
5   21:25   -0.07296177
6   26:30   0.60366540
7   31:35   -0.34679270
8   36:40   -0.07828379
9   41:45   0.89614252
10  46:50   0.65230839

but I would like to keep the row names of my matrix, to have something like this in the row.names:

    row.names   x
1   1966:1970   0.41739378
2   1971:1975   0.96117176
3   1976:1980   -0.54342033
4   1981:1985   0.09633428
5   1986:1990   -0.07296177
6   1991:1995   0.60366540
7   1996:2000   -0.34679270
8   2001:2005   -0.07828379
9   2006:2010   0.89614252
10  2011:2015   0.65230839

I have tried something like that, but doesn't work

running(test[,1], test[,2], fun=cor, width=5, by=5, rownames=rownames(test)) 

some direction?

4

2 回答 2

3

这会从 run.test 中拆分名称(这是一个命名向量,而不是您显示的数据框对象)。然后我抓取名字的向量,强制转换为数字并从测试数据框中提取。然后对第二个名称执行相同的操作并将结果粘贴在一起:

 rn <- strsplit(names(run.test) , ":")

 as.numeric(sapply(rn, "[", 1))
# [1]  1  6 11 16 21 26 31 36 41 46

 names(run.test) <- paste(rownames(test)[as.numeric(sapply(rn, "[", 1))] ,
                          rownames(test)[as.numeric(sapply(rn, "[", 2))]  , sep=":")
 run.test
#------------
 1966:1970  1971:1975  1976:1980  1981:1985  1986:1990  1991:1995  1996:2000  2001:2005  2006:2010  2011:2015 
 0.5016829 -0.5987129 -0.5026115  0.5441250 -0.4203586 -0.4452988 -0.1111146 -0.5197370 -0.2468734 -0.1138099 
于 2015-04-05T01:57:01.523 回答
3

我认为与其尝试保留名称,不如简单地更改它们,因为显然running无论如何都会使用间隔作为向量名称。对于您的示例,您可以这样做:

library(gtools)
years <- 1966:2015 #Define the years interval
test <- matrix(rnorm(100, sd=4), nrow = 50, ncol=2, dimnames= list(years, c("var1", "var2")))
result <- running(test[,1], test[,2], fun=cor, width=5, by=5) #save the output
n <-length(years)
intervals <- paste0(years[seq(1, n, by=5)],":", years[seq(5, n, by=5)]) #create the intervals as strings
names(result) <- intervals #rename the output vector
于 2015-04-05T01:51:35.350 回答