使用变量中的列名直接创建data.tables,并使用变量=:{

时间:2019-06-16 13:58:16

标签: r data.table

到目前为止,我所知道的唯一方法是分两个步骤:使用虚拟名称创建列,然后使用setnames()。我想一步来做,可能有一些参数/选项,但是找不到它

# the awkward way I have found so far
col_names <- c("one", "two","three")
dt <- data.table()
# add columns with dummy names...
setnames(dt, col_names )

还对能够与:=一起使用变量的方式感兴趣,例如

colNameVar <- "dummy_values"
DT[ , colNameVar := 1:10]

对我来说,这个问题似乎与Select / assign to data.table when variable names are stored in a character vector不重复 在这里,我问有关创建data.table的问题,标题中的单词“ creating”。 这与已经创建数据表时完全不同,后者是表示为重复的问题的主题,因为后者有明确记录的已知方法,在我在此询问的情况下是行不通的。

PS。请注意@ Ronak Shah在评论中指出的类似问题:Create empty data frame with column names by assigning a string vector?

1 个答案:

答案 0 :(得分:1)

对于第一个问题,我不确定,但是您可能想尝试看看<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> 是否对创建带有命名列的空data.table有帮助。

关于第二个问题,请尝试

fread

其中DT[, c(nameOfCols) := 10] 是带有要修改的列名称的向量。参见nameOfCols