我有两个长度相同的系列的清单。执行以下代码后,第二个系列的元素要少于第一个。有没有一种通用的方法来删除仅包含n + 1个元素的序列中的最后一个元素,以便列表中的所有序列都具有n个元素?如果我的列表中包含n,n + 1和n + 2个元素的序列组合怎么办?下面是一个最小的可复制示例。
#test
library('urca')
tseries <- list("t1" = c(1,2,1,2,1,2,1,2,1,2,1,2,1,2,1), "t2" = c(1,2,3,4,5,6,7,8,9,10,9,8,7,8,9));
# apply stationarity test to the list of series
adf <- lapply(tseries, function(x) tseries::adf.test(x)$p.value)
adf
# index only series that need differencing
not_stationary <- tseries[which(adf > 0.05)]
stationary <- tseries[which(adf < 0.05)]
not_stationary <- lapply(not_stationary, diff);
# verify
adf <- lapply(not_stationary, function(x) tseries::adf.test(x)$p.value)
adf
now_stationary <- not_stationary
#combine stationary and now_stationary
tseries_diff <- c(stationary, now_stationary)
tseries_diff
#$t1
#[1] 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1
#$t2
#[1] 1 1 1 1 1 1 1 1 1 -1 -1 -1 1 1
因此,总而言之,我想从t1中删除最后一个元素1,但要使用可应用于一系列长度为n和n + 1的列表的代码(而n + 2会很有用)。
谢谢!
答案 0 :(得分:2)
您可以找到最小长度,并简单地获得到该点为止的序列,即
new_series_list <- lapply(tseries_diff, function(i)i[seq(min(lengths(tseries_diff)))])
所以长度现在相同
lengths(new_series_list)
#t1 t2
#14 14
这将适用于任何尺寸系列。它将把长序列修剪成短序列。
答案 1 :(得分:1)
为列表而不是矢量进行了编辑- 如果要处理列表,则要使所有系列的长度最短:
(我修改示例以避免使用库)
#test
mylist <- c(1,1,1,1,1)
mylongerlist <- c(1,1,1,1,1,1,1)
length(mylist)
# [1] 5
length(mylongerlist)
# [1] 7
#combine
tseries_diff <- list("t1" = mylist, "t2" = mylongerlist)
tseries_diff
# $t1
# [1] 1 1 1 1 1
#
# $t2
# [1] 1 1 1 1 1 1 1
# on the fly approach to truncate
lapply(tseries_diff, function(x) { length(x) <- min(lengths(tseries_diff)); x })
# $t1
# [1] 1 1 1 1 1
#
# $t2
# [1] 1 1 1 1 1
还有一个功能
# As a reusable function for clear code
reduceToShortestLength <- function(toCut) {
# takes a list and cuts the tail off of any series longer than the shortest
lapply(toCut, function(x) { length(x) <- min(lengths(tseries_diff)); x })
}
reduceToShortestLength(tseries_diff)
# $t1
# [1] 1 1 1 1 1
#
# $t2
# [1] 1 1 1 1 1
以下为原文(以防万一有人像我起初那样认为向量)
我认为您在问如何将向量截短到最短的长度。 head
函数在基本R中表现良好。
动态方法:
> mylist <- c(1,1,1,1,1)
> mylongerlist <- c(1,1,1,1,1,1,1)
> length(mylist)
[1] 5
> length(mylongerlist)
[1] 7
> x <- head(mylongerlist, length(mylist))
> length(x)
[1] 5
可以这样写一个函数:
> reduceToShorterLength<- function(toshorten, template) { head(toshorten, length(template))}
> x <- reduceToShorterLength(mylongerlist, mylist)
> length(x)
[1] 5