在 R 中选择数据表列的子集
在本文中,我们将讨论如何在 R 编程语言中选择数据表列的子集。
让我们使用矩阵创建一个数据表。首先,我们需要在工作空间中加载data.table包。
Installation
install.packages(“data.table”)
Loading
library(“data.table”)
使用中的数据集:
方法 1:使用 []
我们可以通过索引运算符选择数据表列的子集 - []
句法:
datatable[ , c(columns), with = FALSE]
在哪里,
- datatable 是输入数据表
- 列是要选择的数据表中的列
- with =FALSE 是一个可选参数
示例:从数据表中选择列子集的 R 程序
R
# load data.table package
library("data.table")
# create data table with matrix with 20 elements
# 4 rows and 5 columns
data= data.table(matrix(1:20, nrow=4,ncol = 5))
# display the subset that include v1 and v3 columns
print(data[ , c("V1", "V3"), with = FALSE])
# display the subset that include v1 , v2 and v3 columns
print(data[ , c("V1","V2", "V3"), with = FALSE])
# display the subset that include v2,v3,v4 and v5 columns
print(data[ , c("V2", "V3","V4","V5"), with = FALSE])
R
# load data.table package
library("data.table")
# create data table with matrix with 20 elements
# 4 rows and 5 columns
data= data.table(matrix(1:20, nrow=4,ncol = 5))
# display the subset that exclude v1 and v3 columns
print(data[ , !c("V1", "V3"), with = FALSE])
# display the subset that exclude v1 , v2 and v3 columns
print(data[ , !c("V1","V2", "V3"), with = FALSE])
# display the subset that exclude v2,v3,v4 and v5 columns
print(data[ , !c("V2", "V3","V4","V5"), with = FALSE])
输出:
方法2:使用!
使用 !列之前的运算符足以通过这种方法完成工作。这里我们不包括从数据表中选择的子集
句法:
datatable[ , !c(columns), with = FALSE]
在哪里,
- datatable 是输入数据表
- 列是要选择的数据表中的列
示例:从数据表中选择列的 R 程序
电阻
# load data.table package
library("data.table")
# create data table with matrix with 20 elements
# 4 rows and 5 columns
data= data.table(matrix(1:20, nrow=4,ncol = 5))
# display the subset that exclude v1 and v3 columns
print(data[ , !c("V1", "V3"), with = FALSE])
# display the subset that exclude v1 , v2 and v3 columns
print(data[ , !c("V1","V2", "V3"), with = FALSE])
# display the subset that exclude v2,v3,v4 and v5 columns
print(data[ , !c("V2", "V3","V4","V5"), with = FALSE])
输出: