I have a data frame with two date columns (from and to). I'd like to create a year and quarter sequence between the two dates and then reshape to transform to a tall data frame.
df <- structure(list(id = 1:4, from = structure(c(1L, 1L, 2L, 2L), .Label = c("2018-01-01", "2018-04-01"), class = "factor"), to = structure(c(2L, 1L, 4L, 3L), .Label = c("2018-02-01", "2018-04-01", "2018-07-01", "2018-10-01"), class = "factor")), class = "data.frame", row.names = c(NA, -4L))
> df
id from to
1 2018-01-01 2018-04-01
2 2018-01-01 2018-02-01
3 2018-04-01 2018-10-01
4 2018-04-01 2018-07-01
In the example above id 1 is in Q1 and Q2 whereas id 2 is only in Q1.
Desired output:
#id Quarter
#1 Q1 2018
#1 Q2 2018
#2 Q1 2018
#3 Q2 2018
#3 Q3 2018
#3 Q4 2018
#4 Q2 2018
#4 Q3 2018
I'm able to get a quarter sequence using seq function:
dsq <- seq(ymd('2018-01-01'),ymd('2018-04-01'), by = 'quarters')
paste0("Q", lapply(dsq, quarter), " ", lapply(dsq, year))
but I'm looking for a way to reshape my table using the obtained sequence.
Any help is appreciated.
答案 0 :(得分:1)
我们可以做到
getPhoto(){
console.log("In get Photo Method");
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
console.log("Check Image"+imageData);},
(err) => {
console.log("Check Error Red"+err);
});}
或尝试使用library(zoo)
library(tidyverse)
df %>%
mutate_at(2:3, zoo::as.yearqtr, format = "%Y-%m-%d") %>%
gather(key, Quarter, -id) %>%
select(-key) %>%
arrange(id)
# id Quarter
#1 1 2018 Q1
#2 1 2018 Q2
#3 2 2018 Q1
#4 2 2018 Q1
#5 3 2018 Q2
#6 3 2018 Q4
#7 4 2018 Q2
#8 4 2018 Q3
data.table
如果library(data.table)
setDT(df)[, `:=`(from = as.Date(from),
to = as.Date(to))
][, .(Quarter = as.yearqtr(seq(from, to, "quarter"))), by = id]
和from
已经是to
类,则简化为
date
答案 1 :(得分:0)
您可以在代码中添加一些额外的功能:
f <- function(x,y) {
dsq <- seq(ymd(x),ymd(y), by = 'quarters')
paste0("Q", lapply(dsq, quarter), " ", lapply(dsq, year))
}
df %>% rowwise %>% mutate(quarter=list(f(from,to))) %>% unnest
## A tibble: 8 x 4
# id from to quarter
# <int> <fct> <fct> <chr>
#1 1 2018-01-01 2018-04-01 Q1 2018
#2 1 2018-01-01 2018-04-01 Q2 2018
#3 2 2018-01-01 2018-02-01 Q1 2018
#4 3 2018-04-01 2018-10-01 Q2 2018
#5 3 2018-04-01 2018-10-01 Q3 2018
#6 3 2018-04-01 2018-10-01 Q4 2018
#7 4 2018-04-01 2018-07-01 Q2 2018
#8 4 2018-04-01 2018-07-01 Q3 2018