将1个列表中的日期值更改为另一个列表中的第i个日期值

时间:2017-01-15 09:02:57

标签: r lapply

我有一系列日期

daysList <- seq(as.Date('2016-12-29'),as.Date('2017-01-01'),by="days")

countList,具有递减值daysList的列表从0到最后一个值:

countList <- list()
for (i in (length(daysList)-1):0) {
res <- 0:i
countList <- append(countList, list(res))
}

最后生成另一个列表,days_decremented,此列表将daysList中的日期值分配给countList。

days_decrement <- lapply(rev(seq_along(daysList)), tail, x=daysList)

我需要生成另一个列表,该列表会更改days_decrement中的值以在daysList中重复ith值。

所以结果将类似于:

>daysCopy
[[1]]
[1] "2016-12-29" "2016-12-29" "2016-12-29" "2016-12-29"
[[2]]
[1] "2016-12-30" "2016-12-30" "2016-12-30"
[[3]]
[1] "2016-12-31" "2016-12-31"
[[4]]
[1] "2017-01-01"

我尝试了过多的lapply,rep_len甚至尝试在主要的days_decrement循环中循环,将[[i]] [i]值分配给daysList [i]值并且我无处可去。

像往常一样,我想错过了一个lapply实现。

2 个答案:

答案 0 :(得分:1)

根据您的输出,然后一种方法是将days_decrement的所有日期替换为第一个日期,即

lapply(days_decrement, function(i)replace(i, i != i[1], i[1]))

#[[1]]
#[1] "2016-12-29" "2016-12-29" "2016-12-29" "2016-12-29"
#[[2]]
#[1] "2016-12-30" "2016-12-30" "2016-12-30"
#[[3]]
#[1] "2016-12-31" "2016-12-31"
#[[4]]
#[1] "2017-01-01"

但是,如果您只想直接从countListdaysList进行操作,那么,

 Map(rep, daysList, lapply(countList, length)) 
 #or similarly Map(rep, daysList, lapply(days_decrement, length))

#[[1]]
#[1] "2016-12-29" "2016-12-29" "2016-12-29" "2016-12-29"
#[[2]]
#[1] "2016-12-30" "2016-12-30" "2016-12-30"
#[[3]]
#[1] "2016-12-31" "2016-12-31"
#[[4]]
#[1] "2017-01-01"

答案 1 :(得分:0)

对于这类工作,您可以尝试使用purrr包和功能编程。 map函数及其朋友“有点像”lapply但是它们在使用时显示更加一致和强大,并且管道语法非常简洁。

# your input
daysList <- seq(as.Date('2016-12-29'),as.Date('2017-01-01'),by="days")

# using purrr for creating your two lists
library(purrr)

# creating another kind of countlist
countList <- 1:length(daysList) %>% map(~.x:length(daysList))
countList
#> [[1]]
#> [1] 1 2 3 4
#> 
#> [[2]]
#> [1] 2 3 4
#> 
#> [[3]]
#> [1] 3 4
#> 
#> [[4]]
#> [1] 4

days_decrement <- rerun(length(daysList), daysList) %>% 
  map2(countList, ~.x[.y])
days_decrement
#> [[1]]
#> [1] "2016-12-29" "2016-12-30" "2016-12-31" "2017-01-01"
#> 
#> [[2]]
#> [1] "2016-12-30" "2016-12-31" "2017-01-01"
#> 
#> [[3]]
#> [1] "2016-12-31" "2017-01-01"
#> 
#> [[4]]
#> [1] "2017-01-01"

# creating the one you asked
daysCopy <- map2(daysList, length(daysList):1, rep)
daysCopy
#> [[1]]
#> [1] "2016-12-29" "2016-12-29" "2016-12-29" "2016-12-29"
#> 
#> [[2]]
#> [1] "2016-12-30" "2016-12-30" "2016-12-30"
#> 
#> [[3]]
#> [1] "2016-12-31" "2016-12-31"
#> 
#> [[4]]
#> [1] "2017-01-01"