Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/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
R 添加序列的列计数重复_R_Dplyr_Tidyverse - Fatal编程技术网

R 添加序列的列计数重复

R 添加序列的列计数重复,r,dplyr,tidyverse,R,Dplyr,Tidyverse,我试图在数据框中添加一列,用于计算序列运行了多少次——在本例中,是12个月 我从月份和年份开始,但为了进行分析,我需要使用调整后的month\u lag列 year.reprex <- rep(1982:2015, each=12) month.reprex <- rep(1:12, times=34) df <- cbind(year.reprex, month.reprex) %>% as_tibble() %>% mutate( month

我试图在数据框中添加一列,用于计算序列运行了多少次——在本例中,是12个月

我从月份和年份开始,但为了进行分析,我需要使用调整后的
month\u lag

year.reprex <- rep(1982:2015, each=12)
month.reprex <- rep(1:12, times=34)
df <- cbind(year.reprex, month.reprex) %>% 
  as_tibble() %>% 
  mutate(
    month_lag = ifelse(month.reprex < 12, month.reprex+1, 1))

year.reprex我们可以在
month\u lag
为1时增加一个计数器,可以使用
cumsum

library(dplyr)

df %>% mutate(year_lag = cumsum(month_lag == 1) + 1)

# year.reprex month.reprex month_lag   year_lag
#         <int>        <int>     <dbl>    <dbl>
# 1        1982            1         2        1
# 2        1982            2         3        1
# 3        1982            3         4        1
# 4        1982            4         5        1
# 5        1982            5         6        1
# 6        1982            6         7        1
# 7        1982            7         8        1
#....
库(dplyr)
df%>%变异(年滞后=累计(月滞后==1)+1)
#year.reprex month.reprex month\u lag year\u lag
#                          
# 1        1982            1         2        1
# 2        1982            2         3        1
# 3        1982            3         4        1
# 4        1982            4         5        1
# 5        1982            5         6        1
# 6        1982            6         7        1
# 7        1982            7         8        1
#....
或者在R底

df$year_lag <- cumsum(df$month_lag == 1) + 1

df$year\u lag是!!我实际上需要在你的代码中输入
month\u lag==1
,所以
year\u lag
month\u lag
达到1而不是12时,就会出现
year\u lag
,但这就解决了这个问题。谢谢