r - 更改data.table r中的多个列

标签 r data.table

我正在寻找一种方法来操作 R 中 data.table 中的多个列。由于我必须动态处理列以及第二个输入,因此我无法找到答案。

这个想法是通过将所有值除以日期值来索引某个日期的两个或多个系列,例如:

set.seed(132)
# simulate some data
dt <- data.table(date = seq(from = as.Date("2000-01-01"), by = "days", length.out = 10),
                 X1 = cumsum(rnorm(10)),
                 X2 = cumsum(rnorm(10)))

# set a date for the index
indexDate <- as.Date("2000-01-05")

# get the column names to be able to select the columns dynamically
cols <- colnames(dt)
cols <- cols[substr(cols, 1, 1) == "X"]

第 1 部分:简单的 data.frame/apply 方法
df <- as.data.frame(dt)
# get the right rownumber for the indexDate
rownum <- max((1:nrow(df))*(df$date==indexDate))

# use apply to iterate over all columns
df[, cols] <- apply(df[, cols], 
                    2, 
                    function(x, i){x / x[i]}, i = rownum)

第 2 部分:(快速)data.table 方法
到目前为止,我的 data.table 方法如下所示:
for(nam in cols) {
  div <- as.numeric(dt[rownum, nam, with = FALSE])
  dt[ , 
     nam := dt[,nam, with = FALSE] / div,
     with=FALSE]
}

尤其是所有的 with = FALSE 看起来都不是很像 data.table。

您知道执行此操作的任何更快/更优雅的方法吗?

任何想法都将不胜感激!

最佳答案

一种选择是使用set,因为它涉及多个列。使用 set 的好处是它会避免 [.data.table 的开销并使其更快。

library(data.table)
for(j in cols){
  set(dt, i=NULL, j=j, value= dt[[j]]/dt[[j]][rownum])
}

或者稍微慢一点的选择是
dt[, (cols) :=lapply(.SD, function(x) x/x[rownum]), .SDcols=cols]

关于r - 更改data.table r中的多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30277368/

相关文章:

r - R 中矩阵的每一行与另一个矩阵的叉积

r - 如何从 OS X 完全卸载 R

r - R 中的等效案例陈述

r - 是否可以将 `data.table` 中的 fwrite 与 gzfile 一起使用?

r - data.table - 检查一列是否在另一(列表)列中

滚动连接 : roll forwards and backwards

R:逐行比较多列字符串与单列字符串

r - 从矢量值命名对象

r - 使用 data.table 中的 fread() 会导致 R session 中止

R:根据其他列条件比较列中的元素?