Home > front end >  Add header and first column
Add header and first column

Time:12-07

I have two data frames such as df1 and df2.

df1 = id a1 a2 a3 a4 
     21 .2 .4 .1 .7
     22 .4 .5 .1 .2
df2 = .2 .4 .2 .3
      .3 .5 .2 .1

How to add the header such as "a1, a2, a3 and a4" and first column (id, 21, 22) of df1 in df2?

CodePudding user response:

This will add the first column of df1 to df2-

df2 <- cbind(df1$id, df2)

Then, you can use this command and it will set the headers of df2 same as headers of df1

colnames(df2) <- colnames(df1) 

CodePudding user response:

Another solution with the use the setNames function:

 df2 <- setNames(df1, c("id","a1","a2", "a3","a4"))

or this to change column name by colnames function.

colnames(df2)[1]<-paste("id")  
colnames(df2)[2]<-paste("a1")  
colnames(df2)[3]<-paste("a2")  
colnames(df2)[4]<-paste("a3") 

Sample data:

df1 = data.frame("id"=c(21,22), "a1"=c(.2,.4 ), "a2"=c(.4,.5), "a3"=c(.1,.1), " a4"=c(.7,.2))

df2= data.frame ("id2"=c(.2,.3), "a1_2"=c(.4,.5), "a2_2"=c(.2,.2), "a3_2"=c(.3,.1))
  •  Tags:  
  • r
  • Related