我有一个data.frame,其中我想创建一个新的列,对样本的发源期进行分类。每个周期从8月1日开始,到7月31日结束。目前,第1期为01/8月/2001至31/7月/2002,第2期为01/Aug/2002至31/7月/2003。
我一直在尝试dplyr,因为我想要一个整洁的解决方案。
下面是data.frame的一个示例
Date <- seq(as.Date("2001/08/01"), by = "month", length.out = 60)
AHD <- rnorm(60, mean = 12, sd = 1)
df <- data.frame(Date=Date, AHD = AHD)我可以使用以下方法将data.frame子集为一个句点:
df %>%
group_by(dr = cut(Date, breaks = c(range(Date),
as.Date(c("2001-08-01", "2002-07-31"))), include.lowest=TRUE) )但是,我不知道如何在一个周期序列中这样做,也不知道如何构建新的类别列。我需要一个新的列,说明每一行是否属于句号1、句号2等。
发布于 2019-08-16 00:31:17
我们可以创建一个从min of Date到max的年日期序列,并在cut中使用。
period <- seq(min(df$Date), max(df$Date), by = "1 year")
df$period <- cut(df$Date, breaks = c(period, Inf),
labels = paste0("period", seq_along(period)))
df
# Date AHD period
#1 2001-08-01 10.792934251 period1
#2 2001-09-01 12.277429242 period1
#3 2001-10-01 13.084441177 period1
#4 2001-11-01 9.654302297 period1
#5 2001-12-01 12.429124689 period1
#6 2002-01-01 12.506055892 period1
#7 2002-02-01 11.425260040 period1
#8 2002-03-01 11.453368144 period1
#9 2002-04-01 11.435548001 period1
#10 2002-05-01 11.109962171 period1
#11 2002-06-01 11.522807300 period1
#12 2002-07-01 11.001613555 period1
#13 2002-08-01 11.223746105 period2
#....我们也可以使用findInterval,它提供与cut相同的结果。
df$period <- paste0("period", findInterval(df$Date, period))数据
set.seed(1234)
Date <- seq(as.Date("2001/08/01"), by = "month", length.out = 60)
AHD <- rnorm(60, mean = 12, sd = 1)
df <- data.frame(Date=Date, AHD = AHD)发布于 2019-08-16 00:50:12
下面是一个基于对类似问题here的答案的解决方案
library(tidyverse)
library(zoo)
Date <- seq(as.Date("2001/08/01"), by = "month", length.out = 60)
AHD <- rnorm(60, mean = 12, sd = 1)
df <- data.frame(Date=Date, AHD = AHD)
df=df%>% mutate(period=as.integer(as.yearmon(Date) - 7/12 + 1)-2001)https://stackoverflow.com/questions/57517577
复制相似问题