如何通过条件(没有循环)替换data.table中的元素?

时间:2014-02-13 11:18:30

标签: r data.table

我在第一列有3个data.table工作日,在列的其余部分有数字。   在第一个DT(DT1)中,每列上有7行和n列(n>2)数字数据。剩下的DT (DT2, DT3)有7行2列,有一个数字列。

我想替换每个列中的元素(工作日列除外),其中DT2中的元素小于或等于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)

有没有办法在没有循环的情况下完成它? 请仅使用基础R? 谢谢。

1 个答案:

答案 0 :(得分: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))])

首先,我将所有表合并为Shadow建议。然后,使用我使用DT1中的数据创建的矩阵,我对ifelse使用criteria,这应该为每列回收criteria。然后,我首先使用ifelse替换运算符将data.table转换为a-d:=列,然后分配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) )。以下是我对您的数据所做的工作:

{{1}}