有效地设置第一个月(Efficiently setting month one backwards)

系统教程 行业动态 更新时间:2024-06-14 16:58:29
有效地设置第一个月(Efficiently setting month one backwards)

在我的数据集中,我想创建一个新的变量,其中月份设置为一个倒退。 我可以这样做:

df$month.min.1 <- gsub('1', '12', df$month) df$month.min.1 <- gsub('2', '1', df$month) df$month.min.1 <- gsub('3', '2', df$month) df$month.min.1 <- gsub('4', '3', df$month) ....

由于我也想创建变量,其中月份设置为两个月和三个月后,我想知道是否有更有效的方法来做到这一点?

In my dataset I want to create a new variable in which the month is set one backwards. I can do it like this:

df$month.min.1 <- gsub('1', '12', df$month) df$month.min.1 <- gsub('2', '1', df$month) df$month.min.1 <- gsub('3', '2', df$month) df$month.min.1 <- gsub('4', '3', df$month) ....

As I also want to create variables in which the month is set two and three months backwards, I'm wondering if there is a more efficient way to do this?

最满意答案

这听起来像你只有1到12代表你的“几个月”。 如果是这样的话,你可以写一个像这样的函数:

myfun <- function(x = 1:12, n = 1) c(tail(x, n), head(x, -n)) myfun() # [1] 12 1 2 3 4 5 6 7 8 9 10 11

然后,您可以使用它来创建滞后的值。

一些例子:

set.seed(1) x <- sample(12, 20, replace = TRUE) ## Imagine this is your "month" variable x # [1] 4 5 7 11 3 11 12 8 8 1 3 3 9 5 10 6 9 12 5 10 myfun()[x] ## Default -- set one month backwards # [1] 3 4 6 10 2 10 11 7 7 12 2 2 8 4 9 5 8 11 4 9 myfun(n = 2)[x] ## "n" can be changed # [1] 2 3 5 9 1 9 10 6 6 11 1 1 7 3 8 4 7 10 3 8

It sounds like you just have 1 through 12 to represent your "months". If that is the case, you can write a function something like this:

myfun <- function(x = 1:12, n = 1) c(tail(x, n), head(x, -n)) myfun() # [1] 12 1 2 3 4 5 6 7 8 9 10 11

You can then use that to create your lagged values.

Some examples:

set.seed(1) x <- sample(12, 20, replace = TRUE) ## Imagine this is your "month" variable x # [1] 4 5 7 11 3 11 12 8 8 1 3 3 9 5 10 6 9 12 5 10 myfun()[x] ## Default -- set one month backwards # [1] 3 4 6 10 2 10 11 7 7 12 2 2 8 4 9 5 8 11 4 9 myfun(n = 2)[x] ## "n" can be changed # [1] 2 3 5 9 1 9 10 6 6 11 1 1 7 3 8 4 7 10 3 8

更多推荐

本文发布于:2023-04-15 03:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/8f0691bb7b04378f68f9d2ba39718048.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有效地   第一个月   Efficiently   setting   month

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!