【问题标题】:Enriching a data.table with derived values from another data.table使用来自另一个 data.table 的派生值来丰富一个 data.table
【发布时间】:2016-07-06 16:40:17
【问题描述】:

假设以下data.tables;

> valid_event_rows
                TTimeStamp DeviceIDI             TimeOff AlarmGroup Alarmcode LogType idKey MailSend DownTime
    1: 2011-09-15 11:46:39         4 2011-09-15 14:04:16          1      1111       0   791        1 138 mins
    2: 2011-09-15 11:47:14         4 2011-09-15 14:04:15          1      1015       2   793        0 137 mins
    3: 2011-09-15 11:47:37         4 2011-09-15 14:04:18          1      1001       2   794        0 137 mins
    4: 2011-09-15 11:57:34         4 2011-09-15 13:57:42          1      7111       2   795        0 120 mins
    5: 2011-09-15 14:58:43         4 2011-09-15 17:59:03          1      7111       2   795        0 181 mins
    ...


> observed_failures
          Group  AlarmCode                    Description  ErrorType
  1:     System        916        HW-profile not selected          1
  2:     System       1001                    Manual stop          1
  3:     System       1003     Emergency switch activated          1
  4:     System       1004                  External stop          0
  5:     System       1005        Availability - low wind          W
  ...

我的目标是使用新列 Frequency 扩展 observed_failures 表,其中包含 valid_event_rows 表中相应 Alarmcodecount()


我尝试通过解析第一个表并将所有出现计数到一个新的 DT failures_distribution 然后将 Frequency 列绑定到所需的表中来尝试这样做,但没有成功。

# Generate a High Level view root cause of observed failures
observed_failures <- event_categories[Number %in% event_data$Alarmcode]
observed_failures <- observed_failures[order(Number, decreasing = FALSE)]

# Build a DF with AlarmCode | Frequency
failures_distribution <- (count(sort(valid_event_rows$Alarmcode)))

# Bind the Frequency column to the table
failures_summary <- cbind(observed_failures,failures_distribution$freq)        # BUG (!!!) 
colnames(failures_summary)[5] <- "Frequency"

但这不起作用,因为event_categories 上的某些事件(按设计)是重复的,因此将 cbind 值与频率映射搞砸了。

我可以通过对event_categories 中的重复项进行排序和删除来修复它,但我宁愿了解什么是最合适的内联方式。

请记住,我是 R 新手。

【问题讨论】:

  • 如果你能dput我应该能为你做的数据
  • 试试cbind,而不是merge

标签: r join data.table


【解决方案1】:

您可以尝试dplyrcountvalid_event_rows 中的警报代码,然后left_join 将这些频率添加到observed_failures:

library(dplyr)
frequencies <- count(valid_event_rows, AlarmCode)
failures_summary <- left_join(observed_failures, frequencies, on = 'AlarmCode')

解释魔术:count 对 data.frame 中的行进行计数,按 AlarmCode 分组。输出是一个带有两个变量的新 data.frame:“AlarmCode”和“n”。 left_join 然后使用 on 指定的变量加入 data.frames,通过使用 left_join 保留 observed_failures 中的所有观察结果,并绑定相应的频率(如果有)。

【讨论】:

  • 我几乎到处都能看到对 dplyr 的引用。估计要学了!再次感谢!
猜你喜欢
  • 2021-10-04
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2020-03-20
  • 1970-01-01
相关资源
最近更新 更多