问题描述
R的data.table中有几列(字面上)分别命名为A1,A2,A3,... A50.不幸的是,我的表中的列不是按字母顺序排列的.
I have several columns (literally) named A1, A2, A3, ... A50 in a data.table in R. Unfortunately, columns in my table are not arranged alphabetically.
我想创建一个名为sumA的新列,其中将包含A1 + A2 + ... + A50.
I want to create a new column named sumA, which will contain A1 + A2 + ... + A50.
什么是简单(而不乏味)的方法?
What's a simple (and not tedious) way of doing this?
推荐答案
这里是 Reduce
和 +
library(data.table)
dt[, sumA := Reduce("+", .SD)]
如果还有其他列,即数据集中除"A1:A50"以外的其他列,请使用 .SDcols
指定要选择的列
If there are other columns i.e. columns other than 'A1:A50' in the dataset, use the .SDcols
to specify the columns to select
dt[, sumA := Reduce("+", .SD), .SDcols = paste0("A", 1:50)]
或者如@Arun所述,如果列是有序的,则可以使用:
来选择列
Or as @Arun mentioned, if the columns are ordered, then :
can be used to select the column
dt[, sumA := Reduce("+", .SD), .SDcols = A1:A50]
这篇关于在data.table中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!