使用字符串中的列名初始化R data.table

时间:2018-02-15 06:14:52

标签: r data.table

我想做这样的事情:

> colname <- "a"
> dt <- data.table(colname = c(1,2,3,4))
   a
1: 1
2: 2
3: 3
4: 4

但相反,我明白了:

> colname <- "a"
> dt <- data.table(colname = c(1,2,3,4))
   colname
1:       1
2:       2
3:       3
4:       4

除了创建data.table并在之后分配名称之外,还有其他方法吗?

2 个答案:

答案 0 :(得分:2)

我们可以使用setnamessetnames的优点是,它可以通过提供oldnew参数中的名称来命名所有列或列的子集

dt <- data.table(c(1,2,3,4))
setnames(dt, colname)

我们可以在创建对象本身时包装setnames

dt <- setnames(data.table(c(1,2,3,4)), colname)[]
dt
#   a
#1: 1
#2: 2
#3: 3
#4: 4

答案 1 :(得分:2)

不使用@Entity(tableName = "TB_CLASSES") class TbClass( @ColumnInfo(name = "ID") @PrimaryKey(autoGenerate = true) var id: Int =-1, @ColumnInfo(name = "NAME") var name: String="", @ColumnInfo(name = "CAPTION") var caption: String="", @ColumnInfo(name = "TYPE") var type: String="") @Entity(tableName = "TB_FEATURE_DISA") class TbFeatureDisa( @ColumnInfo(name = "ID") @PrimaryKey(autoGenerate = true) var id: Int=-1, @ColumnInfo(name = "FEATURE_ID") var featureId: Int=-1, @ColumnInfo(name = "DISA_ID") var disaId: Int=-1, @ColumnInfo(name = "IS_SOLVED") var isSolved: Int=-1, @ColumnInfo(name = "DISA_LEVEL") var disaLevel: Double=-0.1, @ColumnInfo(name = "RESOLVER_USER_NAME") var resolverUserName: String="", @ColumnInfo(name = "RESOLVE_TIME") var resolveTime: Date? =null, @ColumnInfo(name = "REPORT_VIST_ID") var reportVisitId: Int=-1, @ColumnInfo(name = "REPORT_FAULT_ID") var reportFaultId: Int=-1, @ColumnInfo(name = "SOLVE_VIST_ID") var solveVisitId: Int=-1, @ColumnInfo(name = "SOLVE_SERVICE_ID") var solveServiceId: Int=-1, @ColumnInfo(name = "SOLVE_FUALT_ID") var solveFaultId: Int=-1) 的另一种方法是使用基函数data.table

names

如果您有一个包含多列的数据框,只需将列名称向量传递给函数> colnames <- "a" > dt <- data.table(c(1,2,3,4)) > dt V1 1: 1 2: 2 3: 3 4: 4 > names(dt) <- colnames > dt a 1: 1 2: 2 3: 3 4: 4