Reputation: 920
In my data, I have a year-week column and hope to create a variable with combining two weeks.
for example, here is my column x,
x = c(201336, 201336, 201336, 201337, 201337, 201340, 201341, 201341, 201342, 201343, 201344, ...)
In x
, 201336 means 36th week of 2013, 201337 means 37th week of 2013 and so on. I want to indicate that
(201336,201337) -> 1
(201338,201339) -> 2
(201340,201341) -> 3
(201342,201343) -> 4
(201344,201345) -> 5
and so on
So, My desired vector is that
x2 = c(1,1,1,1,1,3,3,3,4,4,5,...)
Upvotes: 0
Views: 50
Reputation: 4505
if there is only one year as @Psidom mentioned above, it seems to be:
(x - min(x))%/%2 + 1
[update] If your vector contains entries for different years:
set.seed(112358)
x <- sample(1992:2017,1000, replace = T)
x <- as.integer((x + sample(seq(.1,.52,length.out=length(1992:2017)),
1000,replace = T)
)*100)
x <- x[order(x)]
names(x) <- x%/%100
head(x, 11)
#1992 1992 1992 1992 1992 1992 1992 1992 1992 1992 1992
#199210 199211 199213 199213 199215 199216 199220 199220 199220 199221 199221
tail(x, 11)
#2017 2017 2017 2017 2017 2017 2017 2017 2017 2017 2017
#201736 201738 201740 201740 201741 201741 201743 201745 201746 201750 201752
foo <- function(x){
return((x-min(x))%/%2+1)
}
xm <- unlist(sapply(unique(names(x)), function(i) foo(x[names(x) == i])), use.names = F)
mdf <- data.frame(original = x, modified = xm)
head(mdf)
# original modified
#1 199210 1
#2 199211 1
#3 199213 2
#4 199213 2
#5 199215 3
#6 199216 4
tail(mdf)
# original modified
#995 201741 16
#996 201743 17
#997 201745 18
#998 201746 19
#999 201750 21
#1000 201752 22
Upvotes: 1
Reputation: 23109
This should work for you:
x = c(201336, 201336, 201336, 201337, 201337, 201340, 201341, 201341, 201342, 201343, 201344)
as.integer((x - 201336) / 2) + 1
# [1] 1 1 1 1 1 3 3 3 4 4 5
Upvotes: 0