R语言 向data.table添加多个新列
在这篇文章中,我们将讨论如何在R编程语言中为data.table添加多个新列。要做到这一点,我们将首先安装data.table库,然后加载该库。
语法
install.packages(“data.table”)
安装完所需的包后,下一步是创建表。我们在 “data.table “的帮助下创建一个表,并将该表存储在一个变量中。之后,如果需求仍然存在,可以通过首先创建一个列作为列表,然后通过以下方法之一将其添加到现有的data.table中来增加新的列。
方法1:使用:=
可以使用 := 操作符将一个列添加到现有的数据表中。
语法
:='(data type, constructors)
这里’:’代表固定值,’=’代表值的分配。所以,它们共同代表了固定值的分配。因此,在”:=”的帮助下,我们将在上面的表格中增加两列。因此,要做到这一点,首先我们要创建列,并尝试将数据放入其中,我们将通过创建一个矢量并将数据放入其中来实现。
下面给出了各种例子来支持这一做法。
例子
# Create table using data.table
data <- data.table(x1 = 1:6,
x2 = 3:8)
y1 <- 10:15
y2 <- 4:9
# := is used to add columns in
# our table
data[ , `:=` (y1 = y1, y2 = y2)]
# print the data
data
输出
图3:增加列后的表
我们也可以利用表中已有的数据在表中添加列。在添加数据时,借助冒号和等号,我们定义了列的名称,即z1和z2,然后在添加数据时,将z1列中的’x1’和’x2’相乘,将z2列中的’y1’和’y2’相乘,最后,我们打印表格。
例子
# create the table
data <- data.table(x1 = 1:6,
x2 = 3:8)
# create the columns which we
# are going to be add in table
y1 <- 10:15
y2 <- 4:9
# add the columns with the help
# of ":=" into the table
data[, ':='(y1=y1,y2=y2)]
# create the data in column z1
# and z2 by multiplying x1,x2 for z1
# and by multiplying y1 and y2
# for z2 and add it to table by using ":="
data[, ':='(z1=x1*x2,z2=y1*y2)]
# print the table
data
输出
图6:添加z1和z2后的表格
方法2:使用”. “和 “by”
在这种方法中,我们使用点”. “和 “by”。这里,”. “用于将数据放在新的列中,”by “用于将这些列添加到数据表中。所以,它们一起被用来向表中添加列。
例子
# creating the table
data <- data.table(x1 = 1:6,
x2 = 3:8)
# creating the data of other
# columns
y1 <- 10:15
y2 <- 4:9
# add the above columns into
# the table
data[, ':='(y1=y1,y2=y2)]
# create extra column with the
# help of data in the table
data[, ':='(z1=x1*x2,z2=y1*y2)]
# create new columns by adding the
# column data of existing data
# add those created column to the
# table with the help of by function
data[, .(a1=x1+y1+z1,a2=x2+y2+z2),
by=.(x1,x2,y1,y2,z1,z2)]
输出
图7:添加a1、a2后的表格