简体   繁体   English

R将增量值指定为最小-最大日期范围,按

[英]R give incremental value to range min-max Date, group by

I need to give an incremental value to range min-max (Date), grouped by ISBN. 我需要提供一个增量值, 范围为min-max (日期), ISBN 分组

I have this sample data (with 2 distinct ISBN): 我有以下示例数据(带有2个不同的ISBN):

ISBN  Date
67898 2013-04-01
67898 2013-05-07
67898 2014-11-21
98756 2012-02-18
98756 2014-11-07
98756 2014-11-21

And this is the result I would need: 这就是我需要的结果:

ISBN  Date       IncrValue
67898 2013-04-01    1
67898 2013-05-07    2
67898 2014-11-21    3
98756 2012-02-18    1
98756 2014-11-07    2
98756 2014-11-21    3

How is this possible to achive in R? 如何在R中达到目标?

Just as @StevenBeaupré shows, you can do it with the dplyr package. 就像@StevenBeaupré所示,您可以使用dplyr软件包来实现。 This is another solution using base package. 这是使用基本软件包的另一种解决方案。

# Create a toy data dataset
df <- data.frame(ISBN = rep(c(123, 456), each = 5), Date = seq(as.Date("2000-01-01"), as.Date("2013-01-01"), length.out = 10))

# dplyr solution
library(dplyr)
df %>%
group_by(ISBN) %>%
mutate(IncrValue = row_number())

# Base solution
listed <- split(df, df$ISBN) # split the data frame by the ISBN variable
newcol <- lapply(listed, function(x) {x$IncrValue <- 1:nrow(x); x}) # create a sequence column within each group
df2 <- unsplit(newcol, df$ISBN) # unsplit back together.

Try this in base R: 在尝试此base R:

df$IncrValue <- as.vector(t(aggregate(Date~ISBN, df, order)[,-1]))

data 数据

df <- structure(list(ISBN = c(67898L, 67898L, 67898L, 98756L, 98756L, 
98756L), Date = structure(c(15796, 15832, 16395, 15388, 16381, 
16395), class = "Date")), .Names = c("ISBN", "Date"), class = "data.frame", row.names = c(NA, 
-6L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 R 中允许用户在最小-最大范围内输入? - How to allow user inputs in a min-max range in R? 根据R?中的计数最小-最大范围,在直方图的计数(y轴)上添加间隔。 - Adding breaks to count (y axis) of a histogram according to the count min-max range in R? 为min-max范围创建geom_ribbon - Create geom_ribbon for min-max range 对r中的数据集中的所有变量进行排名和最小-最大范数 - Rank and min-max norm all variables in a dataset in r R中的最小-最大归一化,根据另一列设置最小和最大组 - Min-max normalization in R, setting groups of min and max based on another column 按组计算最小值和最大值(范围) - Calculate min and max (range) by group 重复识别日期/日期时间范围内的最小和最大数值 - Identify Min & Max Numeric Value within Date/Datetime range repeatedly 在 R 中按组提取最小值/最大值 - Extract min/max by group in R 使用Python或R通过最小-最大和标准偏差方法对仅某些列进行归一化 - Normalization by min-max & stand deviation method to only certain columns using Python or R preProc = c(“center”, “scale”) 在插入符号的 package (R) 和 min-max 归一化中的含义 - preProc = c(“center”, “scale”) meaning in caret's package (R) and min-max normalization
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM