CLM
CLM

Reputation: 119

How to transforrm a row in header in a data.frame

I have a large data.frame without header.

I would like to set the 500th row as the header (for columns).

I have looked for examples, but I could not find any. Is there any quick solution?

Upvotes: 1

Views: 74

Answers (2)

Sam Firke
Sam Firke

Reputation: 23064

library(janitor)
row_to_names(dat, 500)

See ?row_to_names for how to specify whether to keep rows 1:499 and row 500 in the data.frame.

Self-promotion alert, I maintain the janitor package. This function was created precisely for this use case so I'm adding it as a late answer.

Upvotes: 0

Ari
Ari

Reputation: 1982

It would help if you provided a reproducible example - it's difficult for me to know what you mean by the "header" of a data.frame. Are you referring to the column names?

Here is reproducible code to create a data.frame with 500 rows:

set.seed(0)
df = data.frame(x=sample(500), y=sample(500), z=sample(500))
head(df)
> head(df)
      x   y   y
  1 449  28 133
  2 133 277 265

Here the column names for df are "x", "y" and "z". You can set them with the colnames() function:

> ?colnames
> colnames(df) = c("a", "new", "header")
> head(df)
    a new header
1 449  28    133
2 133 277    265
3 186 343    342

If you want df's column's names to be the values of the 500th row of df, do it like this

> colnames(df) = df[500,]
> head(df)
  212 369 214
1 449  28 133
2 133 277 265

The first parameter to [,] is the row (in this case 500); the second is the column. Placing no value as the column makes R use all columns.

Upvotes: 3

Related Questions