Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Column names into first row of Data frame in R

Tags:

dataframe

r

I want to change column names of existing dataframe without deleting it.

Those column names i need as a 1st row of my dataframe.

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)

Required Output:

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

I Have tried but not correct.

df1<-as.data.frame(t(as.character(unlist(colnames(df1)))))
  
colnames(df1) <- df[1,]

Does anybody know the correct way??

like image 998
logziii Avatar asked Nov 02 '25 06:11

logziii


2 Answers

In base R, just rbind the column names of the first data and then set the column names

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
like image 130
akrun Avatar answered Nov 04 '25 20:11

akrun


You can first rbind the first row of df on top of dfand then overwrite the namesof dfwith the namesof df1:

df <- rbind(names(df), df)
names(df) <- names(df1)
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  
like image 21
Chris Ruehlemann Avatar answered Nov 04 '25 18:11

Chris Ruehlemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!