case_when在R中的循环/函数

r7knjye2  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(141)

我有时间序列数据,我想从连续天变量(第1 - 7天=第1周,以此类推)创建一个周变量。
这是我目前所做的:

mydf %>%
mutate(week = as.numeric(case_when(
lfday >= 1+0*7 & lfday <= 7+0*7 ~ '1',
lfday >= 1+1*7 & lfday <= 7+1*7 ~ '2',
lfday >= 1+2*7 & lfday <= 7+2*7 ~ '3',
lfday >= 1+3*7 & lfday <= 7+3*7 ~ '4',
lfday >= 1+4*7 & lfday <= 7+4*7 ~ '5',
lfday >= 1+5*7 & lfday <= 7+5*7 ~ '6',
lfday >= 1+6*7 & lfday <= 7+6*7 ~ '7',
lfday >= 1+7*7 & lfday <= 7+7*7 ~ '8',
lfday >= 1+8*7 & lfday <= 7+8*7 ~ '9',
lfday >= 1+9*7 & lfday <= 7+9*7 ~ '10')))

这段代码可以工作,但是我想通过创建一个for循环/函数来避免复制粘贴。然而,我完全是新手,我可能需要一些帮助。我的想法是循环通过两个向量(0 - 9和1 - 10),但老实说我不知道怎么做。提前感谢!

yyyllmsg

yyyllmsg1#

我觉得比这简单多了:

lfday <- 1:70
week <- ceiling(lfday/7)
cbind(lfday,week)

      lfday weeks
 [1,]    1     1
 [2,]    2     1
 [3,]    3     1
 [4,]    4     1
 [5,]    5     1
 [6,]    6     1
 [7,]    7     1
 [8,]    8     2
 [9,]    9     2
[10,]   10     2
[11,]   11     2
[12,]   12     2
[13,]   13     2
[14,]   14     2
[15,]   15     3
[16,]   16     3
[17,]   17     3
[18,]   18     3
[19,]   19     3
[20,]   20     3
[21,]   21     3
[22,]   22     4
[23,]   23     4
[24,]   24     4
[25,]   25     4
[26,]   26     4
[27,]   27     4
[28,]   28     4
[29,]   29     5
[30,]   30     5
[31,]   31     5
[32,]   32     5
[33,]   33     5
[34,]   34     5
[35,]   35     5
[36,]   36     6
[37,]   37     6
[38,]   38     6
[39,]   39     6
[40,]   40     6
[41,]   41     6
[42,]   42     6
[43,]   43     7
[44,]   44     7
[45,]   45     7
[46,]   46     7
[47,]   47     7
[48,]   48     7
[49,]   49     7
[50,]   50     8
[51,]   51     8
[52,]   52     8
[53,]   53     8
[54,]   54     8
[55,]   55     8
[56,]   56     8
[57,]   57     9
[58,]   58     9
[59,]   59     9
[60,]   60     9
[61,]   61     9
[62,]   62     9
[63,]   63     9
[64,]   64    10
[65,]   65    10
[66,]   66    10
[67,]   67    10
[68,]   68    10
[69,]   69    10
[70,]   70    10

相关问题