Letin
Letin

Reputation: 1275

How to give a header to the first side left column of the data frame using R?

This may be like a very small question, but I need some help here.

Lets say I have a data frame (df) in R which reads like this:

    X   Y   Z
Ras 56  89  76
Jyo 76  90  00
Abi 45  88  34
Poo 78  98  54

I wish to give a header to the first column and name it as "Names", so as to get the following output.

Names   X   Y   Z
Ras 56  89  76
Jyo 76  90  00
Abi 45  88  34
Poo 78  98  54

When I check, it gives me the following headers:

> names(df)[1]
X
> names(df)[2]
Y
> names(df)[3]
Z

So I tried something like,

> names(df)[0] <- "Names"

But that did not do anything. Can anyone help me how do I give this "Names" header using R?

Upvotes: 0

Views: 3063

Answers (2)

Ricardo Saporta
Ricardo Saporta

Reputation: 55340

if df is your dataframe, then you would use:

df <- data.frame("names"=rownames(df), df)

Upvotes: 1

Roland
Roland

Reputation: 132676

The first "column" is actually not a column, but the row names. You can create a new column using df$names <- rownames(df). Then you might want to change the row names to a simple index: rownames(df) <- NULL. Row names are part of the data.frame structure; so it is not possible to remove them entirely.

Upvotes: 2

Related Questions