使用特定的迭代在R中创建列表

时间:2018-09-07 08:49:54

标签: r list iteration

我有一个包含10个文件的文件夹,我以S的形式导入R

S<-list.files(S1_path, recursive = TRUE, full.names = TRUE, pattern="S1") 

> S
 [1] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180412T171648_20180412T171715_021437_024E95_BDA1.zip"
 [2] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180424T171648_20180424T171715_021612_02540A_BB21.zip"
 [3] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180506T171649_20180506T171716_021787_025996_98AB.zip"
 [4] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180518T171649_20180518T171716_021962_025F27_A15C.zip"
 [5] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180530T171650_20180530T171717_022137_0264C8_5D94.zip"
 [6] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180611T171651_20180611T171718_022312_026A3D_BBFC.zip"
 [7] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180623T171652_20180623T171719_022487_026F7C_450E.zip"
 [8] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180705T171652_20180705T171719_022662_027499_1B8F.zip"
 [9] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180717T171653_20180717T171720_022837_0279EC_5E5E.zip"
[10] "/shared/Training/EARSEL0918_UrbanClassification_Germany/Original//S1A_IW_SLC__1SDV_20180729T171654_20180729T171721_023012_027F72_97F6.zip"

使用S作为输入,我想创建两个新的differentnet列表。一个在位置[1][3][5][7][9]中包含文件,另一个在位置[2],{{ 1}},[4][6][8]

我正在尝试改编我以前的代码。在这里,我创建了一个空列表,我在[10]上以1到1的顺序填充了列表,而不是按照我想要的方式填充。

S

您有什么建议吗?像input<-list() for (i in S){ input[[i]]<-paste("-Pinput1=", i, sep="") } 一样?

4 个答案:

答案 0 :(得分:1)

这会接近您的需求吗?

library(tidyverse)

list1 <- S[seq(1, 9, 2)] %>% 
  map(~paste0("-Pinput1=", .x))

第一行从列表中提取奇数位置,第二行在每个列表前面粘贴字符串-Pinput1=

答案 1 :(得分:1)

最简单的方法:

even_indexes<-seq(2,10,2) # List of even indexes
odd_indexes<-seq(1,10,2)  # List of odd indexes
paste0("-Pinput1=",df[odd_indexes,])  # Name with odd index
paste0("-Pinput1=",df[even_indexes,]) # Name with even index

答案 2 :(得分:1)

尝试以下示例:

S <- c("a", "b", "c", "d")

S_odd <- paste0("-Pinput1=", S[ c(TRUE, FALSE) ])
S_even <- paste0("-Pinput1=", S[ c(FALSE, TRUE) ])

S_odd
# [1] "-Pinput1=a" "-Pinput1=c"

S_even
# [1] "-Pinput1=b" "-Pinput1=d"

答案 3 :(得分:0)

添加所有想法,我也设法找到了解决方案:

input<-list()
for (i in S[seq(1, 10, 2)]){
  input[[i]]<-paste("-Pinput1=", i, sep="")
}

input<-list()
for (i in S[seq(2, 10, 2)]){
  input[[i]]<-paste("-Pinput1=", i, sep="")
}