[英]How to Make column names the first row in r?
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.
我想将我的列名作为第一行值,并将列名更改为类似 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.
我更改了“想要”部分以反映所需的结果。
you can used the names() function to extract column names of the data frame and row bind that to your data frame.您可以使用 names() function 提取数据框的列名并将其行绑定到您的数据框。 Then use the names() function again to override the existing names to any standard value you want.
然后再次使用 names() function 将现有名称覆盖为您想要的任何标准值。
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.