在data.table中创建新列 [英] Creating new columns in data.table

查看:59
本文介绍了在data.table中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆