我尝试使用数据的第一行重命名列名。
将 %>% 与 colnames()<- 等替换函数一起使用
我反驳的问题是在不破坏列的情况下执行此过程,dplyr pipeline因为我想在重命名列后继续做一些其他的事情。
这篇文章中有关于rename函数 dplyr::rename 的评论,如果您只是(重新)命名许多列中的一些(它需要同时编写旧名称和新名称;请参阅@Richard Scriven 的答案)
但是,在我的真实数据中,列数不是固定的,因此我需要使用类似的方法来选择列 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)%>%
....
Run Code Online (Sandbox Code Playgroud)
选择和重命名列后的预期输出
33 53 94
1 65 4 98
Run Code Online (Sandbox Code Playgroud) 我有下表:
X.5 X.6 X.7 X.8 X.9 X.10 X.11 X.12 X.13
17 Zip CuCurrent PaCurrent PoCurrent Contact Ext Fax email Status
18 74136 0 1 0 918-491-6998 0 918-491-6659 1
19 30329 1 0 0 404-321-5711 1
20 74136 1 0 0 918-523-2516 0 918-523-2522 1
21 80203 0 1 0 303-864-1919 0 1
22 80120 1 0 0 345-098-8890 456 1
Run Code Online (Sandbox Code Playgroud)
如何使第一行'zip,cucurrent,pacurrent ...'成为列标题?
谢谢,
下边是 dput(dat)
dput(dat)结构(列表(X.5 =结构(c(26L,14L,6L,14L,17L,16L),.Label = c("","1104","1234我不知道Ave. ","139.98","300 Morgan St.","30329","312.95","4101 S. 4th Street,Traff","500 Highway 89 North","644.04","656.73","72160", "72336-7000","74136","75501","80120","80203","877.87","地址1","BZip","General …
是否有一种快速的方法(tidyverse可能是API的一部分)将一行转换为data.frame或者tibble有点类似的列名tibble::column_to_rownames?
我意识到有很多方法可以做到这一点,例如有点笨拙:
> df <- head(iris)
>
> df %>%
+ set_colnames(magrittr::extract(., 1,)) %>%
+ magrittr::extract(-1,)
5.1 3.5 1.4 0.2 1
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
Run Code Online (Sandbox Code Playgroud)