简体   繁体   English

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

[英]Initialize R data.table with column name from string

I want to do something like this: 我想做这样的事情:

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

But instead, I get this: 但是,我得到的是:

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

Is there a good way around this besides creating the data.table and assigning the names afterward? 除了创建data.table和事后分配名称之外,还有什么好办法吗?

We can use setnames . 我们可以使用setnames The advantage of setnames is it can be used to name either all the columns or a subset of columns by providing the names in the old and new argument 的优势setnames是它可以通过提供名字被用来命名要么所有的列或列的子集oldnew说法

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

We can wrap setnames while creating the object itself 我们可以在创建对象本身时包装setnames

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

Another way to do so without using data.table is using the base function names 不使用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

If you have a data frame with multiple columns, just pass the vector of column names to the function names . 如果您的数据框具有多列,只需将列名称的向量传递给函数names

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM