Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign names to data frame with as.data.frame function

Tags:

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. (

like image 976
Saul Garcia Avatar asked Mar 28 '17 10:03

Saul Garcia


People also ask

Which function is used to set row names for data frames?

`. rowNamesDF<-` is a (non-generic replacement) function to set row names for data frames, with extra argument make.

What is the function to set column names for a data frame?

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.

How do I get column names from a DataFrame in R?

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.


2 Answers

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())

like image 51
akrun Avatar answered Sep 19 '22 07:09

akrun


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

like image 35
Patrick Bormann Avatar answered Sep 18 '22 07:09

Patrick Bormann