2014-02-13 56 views
0

我有3 data.table與在列的其餘部分第一列和數字平日。 在第一DT(DT1),它有7行和每一列上的數字數據的n列(n>2)。其餘DT (DT2, DT3)有7行2列有一個數字列。如何通過條件(無循環)替換data.table中的元素?

我想用DT3中的元素代替DT2中每個列中的元素(除了Weekdays列),其中元素在DT3中具有相同的工作日。

x = c(8.38877450980392, 7.94021071115013, 7.95032679738562, 7.44576124567474, 
8.83645276292335) 
y = c(83.8877450980392, 79.4021071115013, 79.5032679738562, 74.4576124567474, 
88.3645276292335) 
DT1 = data.table(WeekDay = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), a = abs(rnorm(7)*100), b = abs(rnorm(7)*100), c = abs(rnorm(7)*100), d = abs(rnorm(7)*100)) 
DT2 = data.table(WeekDay = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), criteria = x) 
DT3 = data.table(WeekDay = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), Replace_Value = y) 

有沒有辦法做到沒有循環? 請僅使用base R? 謝謝。

+0

答:你的例子是不可重現的; x,y有5個元素,你的星期有7個。B.爲什麼不合並data.tables – shadow

+0

這是我可恥的錯誤。我打算用7個元素創建x,y。謝謝^^。 – Phongsakorn

回答

0

這應做到:

setkey(DT1, WeekDay) 
setkey(DT2, WeekDay) 
mx.data <- as.matrix(DT1[, letters[1:4], with=F]) 
(DT1[DT2][DT3][, letters[1:4]:=as.data.table(ifelse(mx.data < criteria, Replace_Value, mx.data))]) 

首先,我合併所有的表作爲暗影建議。然後,使用I與數據在DT1創建的矩陣I使用ifelsecriteria反對,這應爲每列回收criteria。然後,我首先把它變成一個data.table到列a-d:=更換運營商分配ifelse的結果。

影子指出,我不得不改變你的標準,所以他們有天權數。另外,我不得不讓你的標準有點大,因爲他們從來沒有(在DT1總是大於crtieria值)滿足。這是我對你的數據做的:

x = c(8.38877450980392, 7.94021071115013, 7.95032679738562, 7.44576124567474, 
     8.83645276292335, 50, 25) 
y = c(83.8877450980392, 79.4021071115013, 79.5032679738562, 74.4576124567474, 
     88.3645276292335, 50, 25) 
set.seed(1) 
DT1 = data.table(WeekDay = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), a = abs(rnorm(7)*100), b = abs(rnorm(7)*100), c = abs(rnorm(7)*100), d = abs(rnorm(7)*100)) 
DT2 = data.table(WeekDay = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), criteria = x * 7) 
DT3 = data.table(WeekDay = c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), Replace_Value = y) 
+0

哦!這對我來說是一種新技術。它工作得很好。謝謝。 – Phongsakorn

+0

@ user3305468,只要這回答您的問題,請考慮將其標記爲已回答。謝謝。 – BrodieG