Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 如何在R中创建一个循环,自动按年度间隔更改我的数据集的日期,并将它们组合在一个数据集中?_Loops_Dplyr - Fatal编程技术网

Loops 如何在R中创建一个循环,自动按年度间隔更改我的数据集的日期,并将它们组合在一个数据集中?

Loops 如何在R中创建一个循环,自动按年度间隔更改我的数据集的日期,并将它们组合在一个数据集中?,loops,dplyr,Loops,Dplyr,请帮助我创建一个循环,使下面的过程更容易。想象一下,我至少需要回到30年前 library(lubridate) m1y <- df %>% mutate(timestamp= timestamp-years(1)) %>% mutate(changes="-1y") m2y <- df %>% mutate(timestamp= timestamp-years(2)) %>% mutate(changes="-2y") m3y <- df %>%

请帮助我创建一个循环,使下面的过程更容易。想象一下,我至少需要回到30年前

library(lubridate)
m1y <- df %>% mutate(timestamp= timestamp-years(1)) %>% mutate(changes="-1y")
m2y <- df %>% mutate(timestamp= timestamp-years(2)) %>% mutate(changes="-2y")
m3y <- df %>% mutate(timestamp= timestamp-years(3)) %>% mutate(changes="-3y")
m4y <- df %>% mutate(timestamp= timestamp-years(4)) %>% mutate(changes="-4y")
m5y <- df %>% mutate(timestamp= timestamp-years(5)) %>% mutate(changes="-5y")
actual <- df %>% mutate(changes="0")
p1y <- df %>% mutate(timestamp= timestamp+years(1)) %>% mutate(changes="+1y")
p2y <- df %>% mutate(timestamp= timestamp+years(2)) %>% mutate(changes="+2y")

data <- rbind(m1y, m2y, m3y, m4y, m5y, actual, p1y, p2y)

R具有为您执行循环的函数,包括base
lappy()
在这种情况下,有一个
purrr::map
版本的
lappy
来输出一个数据帧,而不是一个列表,
map\u df()
,它可以为您组合成一个数据帧。

库(tidyverse)
图书馆(lubridate)
df 1 2015-11-14 10:09:54 44 0.083005689 1年
#>2 2015-11-14 09:47:50 72 0.036271591年
#>3 2015-11-14 08:51:46 37 0.373922823年
#>4 2015-11-14 08:44:06 34 0.003652218年
#> ...

由(v0.3.0)于2019-11-25创建的具有为您执行循环的函数,包括base
lappy()
在这种情况下,有一个
purrr::map
版本的
lappy
来输出一个数据帧,而不是一个列表,
map\u df()
,它可以为您组合成一个数据帧。

库(tidyverse)
图书馆(lubridate)
df 1 2015-11-14 10:09:54 44 0.083005689 1年
#>2 2015-11-14 09:47:50 72 0.036271591年
#>3 2015-11-14 08:51:46 37 0.373922823年
#>4 2015-11-14 08:44:06 34 0.003652218年
#> ...
由(v0.3.0)于2019-11-25创建

structure(list(timestamp = structure(c(1479118194, 1479116870, 
1479113506, 1479113046, 1479112331, 1479111645, 1479111119, 1479110437, 
1479106612, 1479106218, 1479105192), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), heading = c(44L, 72L, 37L, 34L, 14L, 12L, 
15L, 13L, 45L, 14L, 16L), ground.speed1 = c(0.0830056886417697, 
0.0362715909791526, 0.373922822992792, 0.00365221791296628, 0.0486211951021842, 
0.181217669168713, 0.0550965979273319, 0.154570465194361, 1.55730089114108, 
0.259570141800717, 0.00755638734840589)), row.names = c(NA, -11L
), class = "data.frame")