r - R data.table计算新列,但在开头插入

标签 r data.table

在R data.table中,我可以使用以下语法添加新列:

> dt <- data.table(a=c(1,2), b=c(3,4))
> dt[, c := a + b]
> dt
   a b c
1: 1 3 4
2: 2 4 6

但是我将如何在dt的前面插入c,如下所示:
   c a b
1: 4 1 3
2: 6 2 4

我看了看SO,发现有人建议使用cbind作为data.frame,但是在这里使用:=语法对我来说更方便,所以我想知道是否有经过data.table认可的方法。我的data.table大约有100列,所以我不想将它们全部列出。

最佳答案

Update: This feature has now been merged into the latest CRAN version of data.table (starting with v1.11.0), so installing the development version is no longer necessary to use this feature. From the release notes:

  1. setcolorder() now accepts less than ncol(DT) columns to be moved to the front, #592. Thanks @MichaelChirico for the PR.

当前的data.table(v1.10.5)开发版本对setcolorder()进行了更新,通过接受部分列列表,使此方法更加方便。首先提供提供的列,然后按照现有顺序添加所有未指定的列。
Installation instructions for development branch here.
关于开发分支稳定性的注意事项:我已经运行了几个月,以利用v1.10.5中fread()中的多线程版本(如果您处理多GB的.csv文件,那么值得进行更新)并且我已经没有注意到我使用的任何错误或退化。
library(data.table)
DT <- as.data.table(mtcars)
DT[1:5]
    mpg cyl disp  hp drat    wt  qsec vs am gear carb
1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
根据部分列表对列进行重新排序:
setcolorder(DT,c("gear","carb"))
DT[1:5]
现在给
   gear carb  mpg cyl disp  hp drat    wt  qsec vs am
1:    4    4 21.0   6  160 110 3.90 2.620 16.46  0  1
2:    4    4 21.0   6  160 110 3.90 2.875 17.02  0  1
3:    4    1 22.8   4  108  93 3.85 2.320 18.61  1  1
4:    3    1 21.4   6  258 110 3.08 3.215 19.44  1  0
5:    3    2 18.7   8  360 175 3.15 3.440 17.02  0  0

如果出于任何原因您不想更新到开发分支,则以下内容可以在以前的版本(和当前的CRAN)中使用。
newCols <- c("gear","carb")
setcolorder(DT,c(newCols, setdiff(newCols,colnames(DT)) ## (Per Frank's advice in comments)

## the long way I'd always done before seeing setdiff()
## setcolorder(DT,c(newCols,colnames(DT)[which(!colnames(DT) %in% newCols)]))

关于r - R data.table计算新列,但在开头插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48754756/

相关文章:

r - 从数据框到顶点/边数组

r - 在 data.table 上使用 geosphere distm 函数来计算距离

string - R - 获取给定时间段内最常见的字符串值(模式)

r - 有哪些学习 R 的好书、网络资源和项目?

r - 在 R 中转换多个样本的数据

r - 数据表中的.EACHI?

r - 每组填充时间序列的有效方法

r - 在 R 中对数据表中的连续行进行分组

r - 按组对前 500 行进行子集,用于组的子集

r - 在 R 中仅将图例标题的一部分加粗