[英]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
是它可以通过提供名字被用来命名要么所有的列或列的子集old
和new
说法
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.