I am trying to convert a matrix into data frame, and assign the names in one line.
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"))
Output:
V1 V2
1 1 3
2 2 4
Expected Output:
a b
1 1 3
2 2 4
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. (
`. rowNamesDF<-` is a (non-generic replacement) function to set row names for data frames, with extra argument make.
colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector.
To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in. This operation will then return the column you want as a vector.
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
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
If we quote the documentation of ?as.data.frame
S3 method for class 'matrix'
as.data.frame(x, row.names = NULL, optional = FALSE, ..., stringsAsFactors = default.stringsAsFactors())
I know that it's an old question, but is:
as.data.frame %>% colnames<-("Name here")
not also a solution in 'one line' as the original poster wanted, but just with pipes?
All the best, Patrick
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With