Home > Net >  How to replace all variable names with the contents of the first row in a tibble
How to replace all variable names with the contents of the first row in a tibble

Time:02-02

Is there a quick way to replace variable names with the content of the first row of a tibble?

So turning something like this:

Subject  Q1   Q2      Q3
Subject  age  gender  cue
429753   24   1       man
b952x8   23   2       mushroom
264062   19   1       night
53082m   35   1       moon

Into this:

Subject  age  gender  cue
429753   24   1       man
b952x8   23   2       mushroom
264062   19   1       night
53082m   35   1       moon

My dataset has over 100 variables so I'm looking for a way that doesn't involve typing out each old and new variable name.

CodePudding user response:

A possible solution:

df <- structure(list(Subject = c("Subject", "429753", "b952x8", "264062", 
"53082m"), Q1 = c("age", "24", "23", "19", "35"), Q2 = c("gender", 
"1", "2", "1", "1"), Q3 = c("cue", "man", "mushroom", "night", 
"moon")), row.names = c(NA, -5L), class = "data.frame")

names(df) <- df[1,]
df <- df[-1,]  
df

#>   Subject age gender      cue
#> 2  429753  24      1      man
#> 3  b952x8  23      2 mushroom
#> 4  264062  19      1    night
#> 5  53082m  35      1     moon
  •  Tags:  
  • Related