首页 > 解决方案 > 在 R 中创建具有特定迭代的列表

问题描述

我有以下包含日期的数据集:

> dates
 [1] "20180412" "20180424" "20180506" "20180518" "20180530" "20180611" "20180623" "20180705" "20180717" "20180729"

我正在尝试创建一个列表,其中每个位置的名称为 'Coherence_' + 中的第一个和第二个日期dates。所以在output1[1]我会有Coherence_20180412_20180424. 然后在output1[2]I would haveCoherence_20180506_20180518等。

我从这段代码开始,但它没有按照我需要的方式工作:

output1<-list()
for (i in 1:5){
  output1[[i]]<-paste("-Poutput1=", S1_Out_Path,"Coherence_VV_TC", dates[[i]],"_", dates[[i+1]], ".tif", sep="")
}

你有什么建议吗?

标签: rlistloopsfor-loopiteration

解决方案


试试这个:没有循环

even_indexes<-seq(2,10,2) # List of even indexes
odd_indexes<-seq(1,10,2)  # List of odd indexes
print(paste('Coherence',paste(odd_indexes,even_indexes,sep = "_"),sep = "_"))

从这里链接答案:使用特定迭代在 R 中创建列表

更新 (获取列表中的数据)

lst=c(paste('Coherence',paste(odd_indexes,even_indexes,sep = "_"),sep = "_"))

或者

a=c(1:10)
for (i in seq(1, 9, 2)){
 print(paste('Coherence',paste(a[i],a[i+1],sep = "_"),sep = "_"))
}

输出:

[1] "Coherence_1_2"
[1] "Coherence_3_4"
[1] "Coherence_5_6"
[1] "Coherence_7_8"
[1] "Coherence_9_10"

推荐阅读