【发布时间】:2015-01-05 18:13:25
【问题描述】:
我已经开始将data.table 用于大型人口模型。到目前为止,我印象深刻,因为使用 data.table 结构将我的模拟运行时间减少了大约 30%。我正在尝试进一步优化我的代码并包含一个简化的示例。我的两个问题是:
- 是否可以在此代码中使用
:=运算符? - 使用
:=运算符会更快吗(不过,如果我能够回答我的第一个问题,我应该能够回答我的问题 2!)?
我在运行 Windows 7 的机器上使用 R 版本 3.1.2,data.table 版本 1.9.4。
这是我的可重现示例:
library(data.table)
## Create example table and set initial conditions
nYears = 10
exampleTable = data.table(Site = paste("Site", 1:3))
exampleTable[ , growthRate := c(1.1, 1.2, 1.3), ]
exampleTable[ , c(paste("popYears", 0:nYears, sep = "")) := 0, ]
exampleTable[ , "popYears0" := c(10, 12, 13)] # set the initial population size
for(yearIndex in 0:(nYears - 1)){
exampleTable[[paste("popYears", yearIndex + 1, sep = "")]] <-
exampleTable[[paste("popYears", yearIndex, sep = "")]] *
exampleTable[, growthRate]
}
我正在尝试做类似的事情:
for(yearIndex in 0:(nYears - 1)){
exampleTable[ , paste("popYears", yearIndex + 1, sep = "") :=
paste("popYears", yearIndex, sep = "") * growthRate, ]
}
但是,这不起作用,因为粘贴不适用于data.table,例如:
exampleTable[ , paste("popYears", yearIndex + 1, sep = "")]
# [1] "popYears10"
我查看了data.table documentation。 FAQ 的第 2.9 节使用cat,但这会产生空输出。
exampleTable[ , cat(paste("popYears", yearIndex + 1, sep = ""))]
# [1] popYears10NULL
另外,我尝试搜索 Google 和 rseek.org,但没有找到任何东西。如果缺少明显的搜索词,我将不胜感激搜索提示。我一直发现搜索 R 运算符很困难,因为搜索引擎不喜欢符号(例如,“:=”)并且“R”可能含糊不清。
【问题讨论】:
-
对于刚开始的人来说还不错。问题也很好。
-
您可能喜欢
paste0()函数,它是paste(..., sep = "")的快捷方式。节省一点打字时间。 -
看看
set()。示例:for (i in 1:5) set(DT, i, 3L, i+1)比for (i in 1:5) DT[i, z:= i+1]快得多,其中3L是z的位置。
标签: r data.table