Set the Data Frame column as the index of the R. data.frame object

Using R, how do I make a data column as a data index? Suppose I read my data from a CSV file. One of the columns is called Date, and I want to make this column the index of my frame.

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

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

Now how to do it 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. 
+22
r
source share
3 answers

I assume that by "index" you mean line names. You can assign a vector of string names:

 rownames(df) <- df$Date 
+33
source share

The index can be set while reading data, both in pandas and in 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") 
+5
source share

Tidyverse Solution:

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

All Articles