Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - Group variable based on continuous values

I have such a data frame with annual data, however, for some years there is no data (here: 1956, 1961-1964).

dat <- data.frame(Year = c(1950:1955, 1957:1960, 1965:1970),
                  Val = 1:16)
> dat
   Year Val
1  1950   1
2  1951   2
3  1952   3
4  1953   4
5  1954   5
6  1955   6
7  1957   7
8  1958   8
9  1959   9
10 1960  10
11 1965  11
12 1966  12
13 1967  13
14 1968  14
15 1969  15
16 1970  16

I'd like to add a variable "Period" with the min and max years for each period, where a period is defined as a set of continuous years (i.e. 1950-1955, 1957-1960 and 1965-1970). Creating this variable is not a problem itself, but I am stuck on how to do the grouping. Any ideas?

dat %>%
  ...???... %>%
  mutate(Period = paste(min(Year), max(Year), sep = "-"))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create an ID for the continuous periods:

dat$cont_per <- cumsum(!c(TRUE, diff(dat$Year)==1))

And then compute the min/max values based on that. For example, with :

library(data.table)
setDT(dat)
dat[, Period := paste(min(Year), max(Year), sep="-"), by=cont_per]
 dat
    # Year Val cont_per    Period
 # 1: 1950   1        0 1950-1955
 # 2: 1951   2        0 1950-1955
 # 3: 1952   3        0 1950-1955
 # 4: 1953   4        0 1950-1955
 # 5: 1954   5        0 1950-1955
 # 6: 1955   6        0 1950-1955
 # 7: 1957   7        1 1957-1960
 # 8: 1958   8        1 1957-1960
 # 9: 1959   9        1 1957-1960
# 10: 1960  10        1 1957-1960
# 11: 1965  11        2 1965-1970
# 12: 1966  12        2 1965-1970
# 13: 1967  13        2 1965-1970
# 14: 1968  14        2 1965-1970
# 15: 1969  15        2 1965-1970
# 16: 1970  16        2 1965-1970

N.B.: You can also compute the Period directly, without creating the variabel cont_per:

setDT(dat)[, Period := paste(min(Year), max(Year), sep="-"), by=cumsum(!c(TRUE, diff(Year)==1))]
head(dat)
#    Year Val    Period
# 1: 1950   1 1950-1955
# 2: 1951   2 1950-1955
# 3: 1952   3 1950-1955
# 4: 1953   4 1950-1955
# 5: 1954   5 1950-1955
# 6: 1955   6 1950-1955

Similarly, with :

dat %>% 
   group_by(count_per=cumsum(!c(TRUE, diff(dat$Year)==1))) %>% 
   mutate(Period=paste(min(Year), max(Year), sep="-"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...