这是非常稀疏的数据,我将有超过2000个变量,其中大部分都将缺失。每个记录可能设置了一百个变量。这些变量将是字符、逻辑和数字的混合,我知道每个变量的模式。
我认为避免R复制每次更新对象(或一次添加一行)的最佳方法是创建一个空数据框,然后在从JSON文件中提取特定字段后更新它们。但是,在数据框中执行此操作非常缓慢,转移到data.table或dplyr对象会更好,但仍希望将其减少到几分钟而不是几小时。请参见下面的示例:
timeMe <- function() {
set.seed(1)
names = paste0("A", seq(1:1200))
# try with a data frame
# outdf <- data.frame(matrix(NA, nrow=100, ncol=1200, dimnames=list(NULL, names)))
# try with data table
outdf <- data.table(matrix(NA, nrow=100, ncol=1200, dimnames=list(NULL, names)))
for(i in seq(100)) {
# generate 100 columns (real data is in json)
sparse.cols <- sample(1200, 100)
# Each record is coming in as a list
# Each column is either a character, logical, or numeric
sparse.val <- lapply(sparse.cols, function(i) {
if(i < 401) { # logical
sample(c(TRUE, FALSE), 1)
} else if (i < 801) { # numeric
sample(seq(10), 1)
} else { # character
sample(LETTERS, 1)
}
}) # now we have a list with values to populate
names(sparse.val) <- paste0("A", sparse.cols)
# and here is the challenge and what takes a long time.
# want to assign the ith row and the named column with each value
for(x in names(sparse.val)) {
val=sparse.val[[x]]
# this is where the bottleneck is.
# for data frame
# outdf[i, x] <- val
# for data table
outdf[i, x:=val]
}
}
outdf
}
我认为每列的模式可能已经在每次更新时设置和重置,但我也尝试过通过预设每个列类型来解决,但这并没有帮助。
对于我来说,使用数据框架(在上面被注释掉)运行此示例需要约22秒,转换为数据表则只需5秒。我希望有人知道在底层发生了什么,并能提供一种更快的方法来填充数据表。