如何使用dplyr链中数据的第一行更改col名称 [英] how to change col names with the first row of a data in dplyr chain
问题描述
我尝试用数据的第一行重命名列名。
I try to rename the column names with the first row of the data.
等替换功能一起使用在不破坏 dplyr管道
的情况下执行此过程,因为我想在重命名列后继续做其他事情。
The problem that I counter is that doing this process without breaking the dplyr pipeline
as I would like to continue doing some other stuff after renaming the columns.
在这篇文章中有关于 rename
函数
dplyr :: rename的评论,如果您仅(重)命名许多列中的一些(它需要同时输入新旧名称;请参阅@Richard Scriven的答案)
There is comment in this post about rename
function
dplyr::rename may be more convenient if you are only (re)naming a few out of many columns (it requires writing both the old and the new name; see @Richard Scriven's answer)
但是,在我的真实数据中,列数不是固定的,因此我需要使用类似选择列 select(X9:max(ncol(。)))
However, in my real data the number of columns is not fixed and so I need to use something like to select the columns select(X9:max(ncol(.)))
df <- data.frame(replicate(10,sample(100,2,rep=TRUE)))
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 77 40 45 98 75 17 5 33 53 94
2 43 67 82 42 63 90 14 65 4 98
library(dplyr)
df1 <- df %>%
select(X8,X9,X10)%>%
....
选择并重命名列后的预期输出
the expected output after selection and renaming the columns
33 53 94
1 65 4 98
推荐答案
set.seed(502)
df <- data.frame(replicate(10, sample(100, 2, rep=TRUE)))
> df
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 79 6 82 23 36 58 95 30 60 42
2 89 77 9 13 79 97 1 10 48 66
在基数R中我们可以做到
In base R we can do
df1 <- "colnames<-"(df[2 , x <- paste0("X", 8:10)], df[1, x])
> df1
30 60 42
2 10 48 66
这篇关于如何使用dplyr链中数据的第一行更改col名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!