有效地设置第一个月(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 8It 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 11You 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更多推荐
发布评论