gpt4 book ai didi

r - 将列名转换为 R 中数据框的第一行

转载 作者:行者123 更新时间:2023-12-05 03:51:19 26 4
gpt4 key购买 nike

我想更改现有数据框的列名而不删除它。

我需要将这些列名作为数据框的第一行。

eg.

Existing dataframe

df = data.frame(x = c("P1","P2","P3","P4","P5"),
y = c("DC","DC","DC","DC","DC"),
f_1 = c("NA","1","NA","NA","NA"),
f_2= c("NA","1","NA","NA","NA"),
f_3= c("1","7","NA","NA","NA"),
f_4= c("NA","NA","5","NA","NA"),
f_5= c("NA","NA","2","NA","NA"),
stringsAsFactors = FALSE)

I want to change those col names with another data frame column names.

df1 = data.frame(A = c("P1"),
B = c("p2"),
C = c("p3"),
D= c("p4"),
E= c("p8"),
F= c("p9"),
G= c("p8"),
stringsAsFactors = FALSE)

要求的输出:

Df


A B C D E F G
1 x y f_1 f_2 f_3 f_4 f_5
2 P1 DC NA NA 1 NA NA
3 P2 DC 1 1 7 NA NA
4 P3 DC NA NA NA 5 2
5 P4 DC NA NA NA NA NA
6 P5 DC NA NA NA NA NA

我试过了,但不正确。

df1<-as.data.frame(t(as.character(unlist(colnames(df1)))))

colnames(df1) <- df[1,]

有人知道正确的方法吗??

最佳答案

base R中,只需rbind第一个数据的列名,然后设置列名

setNames(rbind(names(df), df), names(df1))
# A B C D E F G
#1 x y f_1 f_2 f_3 f_4 f_5
#2 P1 DC NA NA 1 NA NA
#3 P2 DC 1 1 7 NA NA
#4 P3 DC NA NA NA 5 2
#5 P4 DC NA NA NA NA NA
#6 P5 DC NA NA NA NA NA

关于r - 将列名转换为 R 中数据框的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62960127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com