【问题标题】:Find the frequency with weight用权重找到频率
【发布时间】:2018-06-26 06:46:31
【问题描述】:

我有以下日期数据:

item,Date
camera,10/12/2017
mobile,10/12/2017
mobile,15/12/2017
camera,15/12/2017
mobile,15/12/2017
mobile,15/12/2017
mobile,25/12/2017
mobile,25/12/2017
camera,25/12/2017
camera,25/12/2017
camera,05/01/2018
laptop,05/01/2018
laptop,05/01/2018
computer,05/01/2018

现在我想根据具有动态重量的日期查找项目频率。 动态权重意味着:最新日期的权重为 1,下一个日期(小于最新日期)的权重应小于最新日期的 10% 等... 例如:

我在上述数据集中有 4 个日期。所以重量应该是:

Date        Weight
05/01/2018  1
25/12/2017  .90 (1 - 10% of 1)  
15/12/2017  .81 (.90 - 10% of .90)
10/12/2017  0.729 (.81 - 10% of .81)

新的数据集应该如下所示:

item,Date           Weight
camera,10/12/2017   0.729
mobile,10/12/2017   0.729
mobile,15/12/2017   0.81
camera,15/12/2017   0.81
mobile,15/12/2017   0.81
mobile,15/12/2017   0.81
mobile,25/12/2017   0.90
mobile,25/12/2017   0.90
camera,25/12/2017   0.90
camera,25/12/2017   0.90
camera,05/01/2018   1.0
laptop,05/01/2018   1.0
laptop,05/01/2018   1.0
computer,05/01/2018 1.0

【问题讨论】:

  • 这是什么日期:25/15/2017?而这个15/15/2017?
  • 在索要代码之前先尝试一下。查找dplyr 并尝试group_by 使用date 作为标准...但首先您需要将您的日期转换为您拥有15/15/2017 的真实日期字段...R 不会将其识别为日期....它可以将其视为分类数据,但我仍然会担心您的数据是如何读入的......
  • 抱歉日期有误,我更正了。日期为 mm/dd/yyyy 格式。

标签: r


【解决方案1】:

rleseq_alonginverse.rle 的可能解决方案:

df <- df[order(df$Date, decreasing = TRUE),]

rl <- rle(as.character(df$Date))
rl$values <- seq_along(rl$values) - 1

df$weights <- 0.9 ^ inverse.rle(rl)

给出:

> df[order(df$Date),]
       item       Date weights
1    camera 2017-12-10   0.729
2    mobile 2017-12-10   0.729
3    mobile 2017-12-15   0.810
4    camera 2017-12-15   0.810
5    mobile 2017-12-15   0.810
6    mobile 2017-12-15   0.810
7    mobile 2017-12-25   0.900
8    mobile 2017-12-25   0.900
9    camera 2017-12-25   0.900
10   camera 2017-12-25   0.900
11   camera 2018-01-05   1.000
12   laptop 2018-01-05   1.000
13   laptop 2018-01-05   1.000
14 computer 2018-01-05   1.000

这是做什么的:

  • 使用df[order(df$Date, decreasing = TRUE),],您可以从最近日期到最旧日期对数据框进行排序。如果您的日期列还不是日期格式,请先将其转换为 df$Date &lt;- as.Date(df$Date, '%d/%m/%Y')
  • 使用rl &lt;- rle(as.character(df$Date)),您可以创建日期的行程编码。要了解它的作用,请查看 rle(as.character(df$Date)) 的输出。
  • rle-object 的值替换为seq_along(rl$values) - 1
  • 现在您可以使用0.9 ^ inverse.rle(rl) 计算权重。

【讨论】:

  • 谢谢@Jaap。有用。你能告诉我根据重量查找物品频率的功能吗?你能给我提供学习R的好教程吗?
  • @Ankur 对于频率:aggregate(as.character(weights) ~ weights, df, length)。您可以在info-page of the R-tag 找到很好的资源概览。
  • 您的解决方案是为我提供称重频率,但我需要基于称重的项目频率
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-24
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
相关资源
最近更新 更多