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

Viewed 107875

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.
4 Answers

The index can be set while reading the data, in both pandas and R.

In pandas:

import pandas as pd
df = pd.read_csv('/mydata.csv', index_col="Date")

In R:

df <- read.csv("/mydata.csv", header=TRUE, row.names="Date")

The tidyverse solution:

library(tidyverse)
df %>% column_to_rownames(., var = "Date")

while saving the dataframe use row.names=F e.g. write.csv(prediction.df, "my_file.csv", row.names=F)

Related