假设我们是一名数据库管理员,负责在 SQL 数据库中高效地实现这一点。 数据库规范化的目标之一是减少冗余。
根据 OP 的描述,每只动物有很多(大约 1 M)观察值(多变量、纵向数据),而动物的数量似乎要少得多。
因此,每个动物的常量(或不变)基础数据,例如treatment、date,应与observations 分开保存。
animal_id 是两个表的键,假设 animal_id 是唯一的(顾名思义)。
(请注意,这是 Mallick's answer 使用 treatment 作为密钥的主要区别,它不能保证是唯一的,即两只动物可能会接受相同的处理,并进一步增加冗余。)
单独的表可以节省内存
出于演示目的,正在为 10 只动物创建更真实的“基准”数据,每只动物有 100 万次观察:
library(data.table) # CRAN version 1.10.4 used
# create observations
n_obs <- 1E6L
n_animals <-10L
set.seed(123L)
observations <- data.table(
animal_id = rep(seq_len(n_animals), each = n_obs),
t = rep(seq_len(n_obs), n_animals),
x = rnorm(n_animals * n_obs),
y = rnorm(n_animals * n_obs))
# create animal base data
animals = data.table(
animal_id = seq_len(n_animals),
treatment = wakefield::string(n_animals),
date = wakefield::date_stamp(n_animals, random = TRUE))
这里wakefield 包用于创建虚拟名称和日期。请注意,animal_id 是整数类型。
> str(observations)
Classes ‘data.table’ and 'data.frame': 10000000 obs. of 4 variables:
$ animal_id: int 1 1 1 1 1 1 1 1 1 1 ...
$ t : int 1 2 3 4 5 6 7 8 9 10 ...
$ x : num -0.5605 -0.2302 1.5587 0.0705 0.1293 ...
$ y : num 0.696 -0.537 -3.043 1.849 -1.085 ...
- attr(*, ".internal.selfref")=<externalptr>
> str(animals)
Classes ‘data.table’ and 'data.frame': 10 obs. of 3 variables:
$ animal_id: int 1 2 3 4 5 6 7 8 9 10
$ treatment:Classes 'variable', 'character' atomic [1:10] MADxZ9c6fN ymoJHnvrRx ifdtywJ4jU Q7ZRwnQCsU ...
.. ..- attr(*, "varname")= chr "String"
$ date : variable, format: "2017-07-02" "2016-10-02" ...
- attr(*, ".internal.selfref")=<externalptr>
合并后的大小约为 240 MB:
> object.size(observations)
240001568 bytes
> object.size(animals)
3280 bytes
让我们以此作为参考,并与OP的方法final_dt进行比较:
# join both tables to create equivalent of final_dt
joined <- animals[observations, on = "animal_id"]
大小现在几乎翻了一番(400 MB),内存效率不高。
> object.size(joined)
400003432 bytes
请注意,到目前为止还没有设置 data.table 键。相反,on 参数用于指定要加入的列。如果我们设置key,join会加速,on参数可以省略:
setkey(observations, animal_id)
setkey(animals, animal_id)
joined <- animals[observations]
如何处理单独的表格?
现在,我们已经证明使用两个单独的表可以提高内存效率。
为了后续分析,我们可以汇总每只动物的observations,例如,
observations[, .(.N, mean(x), mean(y)), by = animal_id]
animal_id N V2 V3
1: 1 1000000 -5.214370e-04 -0.0019643145
2: 2 1000000 -1.555513e-03 0.0002489457
3: 3 1000000 1.541233e-06 -0.0005317967
4: 4 1000000 1.775802e-04 0.0016212182
5: 5 1000000 -9.026074e-04 0.0015266330
6: 6 1000000 -1.000892e-03 0.0003284044
7: 7 1000000 1.770055e-04 -0.0018654386
8: 8 1000000 1.919562e-03 0.0008605261
9: 9 1000000 1.175696e-03 0.0005042170
10: 10 1000000 1.681614e-03 0.0020562628
并使用animals 加入聚合
animals[observations[, .(.N, mean(x), mean(y)), by = animal_id]]
animal_id treatment date N V2 V3
1: 1 MADxZ9c6fN 2017-07-02 1000000 -5.214370e-04 -0.0019643145
2: 2 ymoJHnvrRx 2016-10-02 1000000 -1.555513e-03 0.0002489457
3: 3 ifdtywJ4jU 2016-10-02 1000000 1.541233e-06 -0.0005317967
4: 4 Q7ZRwnQCsU 2017-02-02 1000000 1.775802e-04 0.0016212182
5: 5 H2M4V9Dfxz 2017-04-02 1000000 -9.026074e-04 0.0015266330
6: 6 29P3hFxqNY 2017-03-02 1000000 -1.000892e-03 0.0003284044
7: 7 rBxjewyGML 2017-02-02 1000000 1.770055e-04 -0.0018654386
8: 8 gQP8cZhcTT 2017-04-02 1000000 1.919562e-03 0.0008605261
9: 9 0GEOseSshh 2017-07-02 1000000 1.175696e-03 0.0005042170
10: 10 x74yDs2MdT 2017-02-02 1000000 1.681614e-03 0.0020562628
OP 指出他不想强迫他的用户自己使用联接。诚然,键入animals[observations] 比final_dt 需要更多的击键次数。因此,由 OP 决定是否值得节省内存。
这个结果可以被过滤,例如,如果我们想比较具有某些特征的动物,例如,
animals[observations[, .(.N, mean(x), mean(y)), by = animal_id]][date == as.Date("2017-07-02")]
animal_id treatment date N V2 V3
1: 1 MADxZ9c6fN 2017-07-02 1000000 -0.000521437 -0.001964315
2: 9 0GEOseSshh 2017-07-02 1000000 0.001175696 0.000504217
OP 的用例
在this coment 中,OP 描述了一些他希望看到为他的用户透明地实施的用例:
- 创建新列
final_dt[, x2 := 1-x]:由于只涉及观察,这直接转换为observations[, x2 := 1-x]。
-
使用各种标准选择final_dt[t > 5 & treatment == "A"]:这里涉及两个表的列。这可以用data.table 以不同的方式实现(注意条件已针对实际样本数据进行了修改):
animals[observations][t < 5L & treatment %like% "MAD"]
这类似于预期的语法,但比下面的替代方法慢,因为这里过滤条件应用于完整连接的所有行。
更快的替代方法是拆分过滤条件,以便在连接之前过滤observations,以在最终应用基础数据列上的过滤条件之前减少结果集:
animals[observations[t < 5L]][treatment %like% "MAD"]
请注意,这看起来与预期的语法非常相似(少了一次击键)。
如果用户认为这是不可接受的,可以在函数中隐藏加入操作:
# function definition
filter_dt <- function(ani_filter = "", obs_filter = "") {
eval(parse(text = stringr::str_interp(
'animals[observations[${obs_filter}]][${ani_filter}]')))
}
# called by user
filter_dt("treatment %like% 'MAD'", "t < 5L")
animal_id treatment date t x y
1: 1 MADxZ9c6fN 2017-07-02 1 -0.56047565 0.6958622
2: 1 MADxZ9c6fN 2017-07-02 2 -0.23017749 -0.5373377
3: 1 MADxZ9c6fN 2017-07-02 3 1.55870831 -3.0425688
4: 1 MADxZ9c6fN 2017-07-02 4 0.07050839 1.8488057
使用因子减少内存占用
警告:您的里程可能会有所不同,因为以下结论取决于您计算机上整数的内部表示和数据的基数。请参阅Matt Dowle's excellent answer 关于此主题。
Mallick 提到如果将整数偶然存储为数字,可能会浪费内存。这可以证明:
n <- 10000L
# integer vs numeric vs logical
test_obj_size <- data.table(
rep(1, n),
rep(1L, n),
rep(TRUE, n))
str(test_obj_size)
Classes ‘data.table’ and 'data.frame': 10000 obs. of 3 variables:
$ V1: num 1 1 1 1 1 1 1 1 1 1 ...
$ V2: int 1 1 1 1 1 1 1 1 1 1 ...
$ V3: logi TRUE TRUE TRUE TRUE TRUE TRUE ...
- attr(*, ".internal.selfref")=<externalptr>
sapply(test_obj_size, object.size)
V1 V2 V3
80040 40040 40040
请注意,数字向量需要两倍于整数向量的内存。因此,始终使用后缀字符 L 来限定整数常量是一种很好的编程习惯。
如果强制转换为因子,也可以减少字符串的内存消耗:
# character vs factor
test_obj_size <- data.table(
rep("A", n),
rep("AAAAAAAAAAA", n),
rep_len(LETTERS, n),
factor(rep("A", n)),
factor(rep("AAAAAAAAAAA", n)),
factor(rep_len(LETTERS, n)))
str(test_obj_size)
Classes ‘data.table’ and 'data.frame': 10000 obs. of 6 variables:
$ V1: chr "A" "A" "A" "A" ...
$ V2: chr "AAAAAAAAAAA" "AAAAAAAAAAA" "AAAAAAAAAAA" "AAAAAAAAAAA" ...
$ V3: chr "A" "B" "C" "D" ...
$ V4: Factor w/ 1 level "A": 1 1 1 1 1 1 1 1 1 1 ...
$ V5: Factor w/ 1 level "AAAAAAAAAAA": 1 1 1 1 1 1 1 1 1 1 ...
$ V6: Factor w/ 26 levels "A","B","C","D",..: 1 2 3 4 5 6 7 8 9 10 ...
- attr(*, ".internal.selfref")=<externalptr>
sapply(test_obj_size, object.size)
V1 V2 V3 V4 V5 V6
80088 80096 81288 40456 40464 41856
作为因子存储,只需要一半的内存。
Date 和 POSIXct 类也是如此:
# Date & POSIXct vs factor
test_obj_size <- data.table(
rep(as.Date(Sys.time()), n),
rep(as.POSIXct(Sys.time()), n),
factor(rep(as.Date(Sys.time()), n)),
factor(rep(as.POSIXct(Sys.time()), n)))
str(test_obj_size)
Classes ‘data.table’ and 'data.frame': 10000 obs. of 4 variables:
$ V1: Date, format: "2017-08-02" "2017-08-02" "2017-08-02" "2017-08-02" ...
$ V2: POSIXct, format: "2017-08-02 18:25:55" "2017-08-02 18:25:55" "2017-08-02 18:25:55" "2017-08-02 18:25:55" ...
$ V3: Factor w/ 1 level "2017-08-02": 1 1 1 1 1 1 1 1 1 1 ...
$ V4: Factor w/ 1 level "2017-08-02 18:25:55": 1 1 1 1 1 1 1 1 1 1 ...
- attr(*, ".internal.selfref")=<externalptr>
sapply(test_obj_size, object.size)
V1 V2 V3 V4
80248 80304 40464 40480
请注意,data.table() 拒绝创建 POSIXlt 类的列,因为它存储在 40 个字节而不是 8 个字节中。
因此,如果您的应用程序对内存至关重要,则可能值得考虑在适用的情况下使用因子。