首页 > 解决方案 > 根据最短字符串的长度修改列表

问题描述

我有两个系列的列表,它们以相同的长度开始。执行以下代码后,第二个系列的元素比第一个少一个。是否有一种通用方法可以删除仅包含 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 会很有用)。

谢谢!

标签: rlistdata-manipulation

解决方案


您可以找到最小长度并简单地让系列达到该点,即

new_series_list <- lapply(tseries_diff, function(i)i[seq(min(lengths(tseries_diff)))])

所以长度现在是一样的

lengths(new_series_list)
#t1 t2 
#14 14 

这适用于任何尺寸的系列。它将把长系列修剪成短系列。


推荐阅读