使用as.data.frame函数为数据框分配名称 [英] Assign names to data frame with as.data.frame function
问题描述
我正在尝试将矩阵转换为数据框,并在一行中分配名称。
I am trying to convert a matrix into data frame, and assign the names in one line.
当我使用?as.data.frame
时,有一个名为 col的参数。名称
似乎对我不起作用,我做错了什么吗?
As I used ?as.data.frame
there is a parameter called col.names
which doesn't seem to work for me, am I doing something wrong?
as.data.frame(matrix(c(1:4), nrow=2), col.names=c("a","b"))
输出:
V1 V2
1 1 3
2 2 4
预期输出:
a b
1 1 3
2 2 4
我知道以后可以用`colnames(matrix)= c( a, b)来分配它,但是我只是想知道是否可以在一行中完成它。 (
I know I can assign it later with `colnames(matrix) = c("a,"b), but i am just wondering if it is possible to do it in one line. (
推荐答案
我们可以在假名
自变量> matrix ,当转换为 data.frame
We can use dimnames
argument in matrix
and this will return with the column names as such when converting to data.frame
as.data.frame(matrix(1:4, nrow=2, dimnames = list(NULL, c("a", "b"))))
# a b
#1 1 3
#2 2 4
OP的代码, matrix
输出没有任何列名,因此 as.data.frame
创建列名作为'V1',默认为'V2'。 col.names
参数不是 as.data.frame
class
matrix
,所以它没有任何作用
while in the OP's code, the matrix
output didn't have any column names, so as.data.frame
creates column names as 'V1', 'V2' by default. The col.names
argument is not as.data.frame
for class
matrix
, so it didn't have any effect
如果我们引用?as.data.frame
S3类'矩阵'的方法
S3 method for class 'matrix'
as.data.frame(x,row.names = NULL,可选= FALSE,...,
stringsAsFactors =默认.stringsAsFactors())
as.data.frame(x, row.names = NULL, optional = FALSE, ..., stringsAsFactors = default.stringsAsFactors())
这篇关于使用as.data.frame函数为数据框分配名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!