Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a Data Frame Column as the Index of R data.frame object

Tags:

r

Using R, how do I make a column of a dataframe the dataframe's index? Lets assume I read in my data from a .csv file. One of the columns is called 'Date' and I want to make that column the index of my dataframe.

For example in Python, NumPy, Pandas; I would do the following:

df = pd.read_csv('/mydata.csv') d = df.set_index('Date') 

Now how do I do that in R?

I tried in R:

df <- read.csv("/mydata.csv") d <- data.frame(V1=df['Date']) # or d <- data.frame(Index=df['Date'])  # but these just make a new dataframe with one 'Date' column.  #The Index is still 0,1,2,3... and not my Dates. 
like image 350
brno792 Avatar asked Dec 17 '13 19:12

brno792


People also ask

How do you set a column in a DataFrame as an index?

We can set a specific column or multiple columns as an index in pandas DataFrame. Create a list of column labels to be used to set an index. We need to pass the column or list of column labels as input to the DataFrame. set_index() function to set it as an index of DataFrame.


1 Answers

I assume that by "Index" you mean row names. You can assign to the row names vector:

rownames(df) <- df$Date 
like image 186
Matthew Lundberg Avatar answered Sep 22 '22 03:09

Matthew Lundberg