Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbers as column names of data frames

Tags:

Is there a reason why R won't allow me to have a number as the column name of my dataframe?

Also noticed that if i do data.frame(XX) it adds an X to all the column headers that have numbers at the front.

like image 345
Nathaniel Saxe Avatar asked Aug 06 '10 10:08

Nathaniel Saxe


People also ask

Can column names be numbers?

Names in MySQL can start with a digit, but cannot be entirely digits — they cannot be confusable with an integer. So, no.

Can column names be numbers in R?

Yes, because R won't allow names of objects to start with numbers.

How do I get the column name for a data frame?

To access the names of a Pandas dataframe, we can the method columns(). For example, if our dataframe is called df we just type print(df. columns) to get all the columns of the Pandas dataframe. After this, we can work with the columns to access certain columns, rename a column, and so on.

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

Works for me

data.frame(`1`=rnorm(3), `2`=head(letters,3), check.names=FALSE) #        1 2 # 1 0.5019 a # 2 1.1148 b # 3 0.4787 c 
like image 75
Marek Avatar answered Nov 05 '22 22:11

Marek


Yes, because R won't allow names of objects to start with numbers. If you were to call attach() with the data.frame, this would cause some issues.

data.frame (and read.table) function has the check.names parameter (default is TRUE)

If TRUE then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names and are not duplicated. If necessary they are adjusted (by make.names) so that they are.

From ?make.names:

A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number. [...] The character "X" is prepended if necessary.

like image 28
Shane Avatar answered Nov 05 '22 20:11

Shane