【问题标题】:Create list with specific iteration in R在 R 中创建具有特定迭代的列表
【发布时间】:2018-09-07 09:51:33
【问题描述】:

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

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

我正在尝试创建一个列表,其中每个位置的名称为“Coherence_”+dates 中的第一个和第二个日期。所以在output1[1] 我会有Coherence_20180412_20180424。然后在output1[2] 我会有Coherence_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="")
}

你有什么建议吗?

M

【问题讨论】:

  • matrix(dates, 2) 然后在上面使用apply(..., 2, ...)

标签: r list loops for-loop iteration


【解决方案1】:

试试这个: 无循环

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 = "_"))

从这里链接答案:Create list in R with specific iteration

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

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"

【讨论】:

  • 如何将结果保存为列表,其中每个输出位于[1][2] 等位置。
【解决方案2】:

您可以使用paste 对向量进行操作的功能创建这些模式:

dates <- c("20180412", "20180424", "20180506", "20180518", "20180530", 
"20180611", "20180623", "20180705", "20180717", "20180729")
paste("Coherence", dates[1:length(dates)-1], dates[2:length(dates)], sep="_")
[1] "Coherence_20180412_20180424" "Coherence_20180424_20180506" "Coherence_20180506_20180518"
[4] "Coherence_20180518_20180530" "Coherence_20180530_20180611" "Coherence_20180611_20180623"
[7] "Coherence_20180623_20180705" "Coherence_20180705_20180717" "Coherence_20180717_20180729"

或者其他简单的模式可以生成为:

paste("Coherence", dates[seq(1, length(dates), 2)], dates[seq(2, length(dates), 2)], sep="_")
[1] "Coherence_20180412_20180424" "Coherence_20180506_20180518" "Coherence_20180530_20180611"
[4] "Coherence_20180623_20180705" "Coherence_20180717_20180729"

【讨论】:

    【解决方案3】:

    你可以使用matrix(..., nrow=2):

    dates <- c("20180412", "20180424", "20180506", "20180518", "20180530", "20180611", "20180623", "20180705", "20180717", "20180729")
    paste0("Coherence_", apply(matrix(dates, 2), 2, FUN=paste0, collapse="_"))
    # > paste0("Coherence_", apply(matrix(dates, 2), 2, FUN=paste0, collapse="_"))
    # [1] "Coherence_20180412_20180424" "Coherence_20180506_20180518" "Coherence_20180530_20180611" "Coherence_20180623_20180705"
    # [5] "Coherence_20180717_20180729"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2020-06-09
      • 1970-01-01
      相关资源
      最近更新 更多