r - 根据最短字符串的长度修改列表
问题描述
我有两个系列的列表,它们以相同的长度开始。执行以下代码后,第二个系列的元素比第一个少一个。是否有一种通用方法可以删除仅包含 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 会很有用)。
谢谢!
解决方案
您可以找到最小长度并简单地让系列达到该点,即
new_series_list <- lapply(tseries_diff, function(i)i[seq(min(lengths(tseries_diff)))])
所以长度现在是一样的
lengths(new_series_list)
#t1 t2
#14 14
这适用于任何尺寸的系列。它将把长系列修剪成短系列。
推荐阅读
- python - 为什么我的程序会响应“列表索引超出范围”?
- python - 聚类分析:从原点到数据框中的质心欧几里得距离的问题
- c# - C# 中的通用 WPF 绑定?
- python-3.x - 面临使用 python3 抓取孟加拉语文本的问题
- c++ - 在 C++ 中执行非阻塞线程
- mysql - MySQL:如何在同一行显示前一天数据和第二天数据
- gradle - JHipster 的 Gitlab CI 失败
- asp.net-core - 为什么回滚后我在 SaveChanges 上收到 DbUpdateConcurrencyException
- c# - 如何在 C# 中标准化花哨的 unicode 字符串?
- java - 从 JPanel 获取课程