代码之家  ›  专栏  ›  技术社区  ›  GCGM

在R中创建具有特定迭代的列表

  •  0
  • GCGM  · 技术社区  · 6 年前

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

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

    我试图创建一个列表,在每个位置,名字是'连贯性'+的第一和第二个日期 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="")
    }
    

    你有什么建议吗?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Saurabh Chauhan    6 年前

    无回路

    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"
    
        2
  •  1
  •   Silpara    6 年前

    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
  •  0
  •   jogo    6 年前

    你可以用 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"