Home > Net >  How to Make column names the first row in r?
How to Make column names the first row in r?

Time:12-03

I have seen may tutorials on making the first row the column names, but nothing explaining how to do the reverse. I would like to have my column names as the first row values and change the column names to something like var1, var2, var3. Can this be done?

I plan to row bind a bunch of data frames later, so they all need the same column names.

q = structure(list(shootings_per100k = c(8105.47466098618, 6925.42653239307
), lawtotal = c(3.00137104283906, 0.903522788541896), felony = c(0.787418655097614, 
0.409578330883717)), row.names = c("mean", "sd"), class = "data.frame")

Have:

     shootings_per100k  lawtotal    felony
mean          8105.475 3.0013710 0.7874187
sd            6925.427 0.9035228 0.4095783

Want:

                  var1      var2      var3                  
var  shootings_per100k  lawtotal    felony
mean          8105.475 3.0013710 0.7874187
sd            6925.427 0.9035228 0.4095783

edit: I just realized that since I plan to row bind several data frames later, it may be best for them to all have the same column names. I changed the 'want' section to reflect the desired outcome.

CodePudding user response:

q <- rbind(colnames(q), round(q, 4))
colnames(q) <- paste0("var", seq_len(ncol(q)))
rownames(q)[1] <- "var"
q
                  var1     var2   var3
var  shootings_per100k lawtotal felony
mean         8105.4747   3.0014 0.7874
sd           6925.4265   0.9035 0.4096

CodePudding user response:

you can used the names() function to extract column names of the data frame and row bind that to your data frame. Then use the names() function again to override the existing names to any standard value you want.

CodePudding user response:

You can also do as follows.

library(tidyverse)

names <- enframe(colnames(df)) %>%
  pivot_wider(-name, names_from = value) %>%
  rename_with( ~ LETTERS[1:length(df)])

data <- as_tibble(df) %>%
  mutate(across(everything(), ~ as.character(.))) %>%
  rename_with(~ LETTERS[1:length(df)])

bind_rows(names, data)

# A tibble: 3 × 3
#   A                 B         C        
#   <chr>             <chr>     <chr>    
# 1 shootings_per100k lawtotal  felony   
# 2 8105.475          3.001371  0.7874187
# 3 6925.427          0.9035228 0.4095783
  • Related