2016-07-06 55 views
-1

假設以下data.tables;利用其他data.table中的派生值豐富data.table

> 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 
    ... 

我的目標與含有count()valid_event_rows表中的各Alarmcode新列Frequency延長observed_failures表。


我已經不成功地試圖通過解析第一個表和所有出現計數到一個新的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.

+1

如果你可以'輸入'數據,我應該可以爲你做這個 –

+0

而不是'cbind'嘗試做一個'merge'。 – ytk

回答

1

您可能會給dplyr一試,count的alarmcodes在valid_event_rows,然後left_join這些頻率的observed_failures:

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

爲了解釋magic:count統計data.frame中的行,按AlarmCode分組。輸出是一個帶有兩個變量的新數據框:'AlarmCode'和'n'。 left_join然後使用on指定的變量連接data.frames,通過使用left_join保留在observed_failures中的所有觀察值,並且相應的頻率(如果有的話)與它綁定。

+0

我幾乎在任何地方都能看到對dplyr的引用。得知它我猜!再次感謝! – Carlos