Bunny Bunny - 8 days ago 6
R Question

How to Use rbind and cbind on Single Dataframe

Sorry for the wrong question framing.
Iam a newbie,trying to learn R on my own.

I have a scenario like,

t1_df

id name address
1 x india
2 y usa


t2_df

id name address
3 a india
4 b usa


Now i tried to add extra column "msg" using data.frame
i.e

t1_df <- data.frame(t1_df,msg)
t2_df <- data.frame(t2_df,msg)


t1_df

id name address msg
1 x india hi
2 y usa hello


t2_df

id name address msg
3 a india go
4 b usa bye


when i tried to do rbind it gives error as col names are not matching because both df's having different col names

When i tried to cbind on both df's into single dataframe is t, it included all the columns from both df's
i.e

colnames(t)

id name address t1_msg id name address t2_msg


But i would like to get the dataframe as

id name address t1_msg t2_msg
1 x india hi NA
2 y usa hello NA
3 a india NA go
4 b usa NA bye


How can i get the output as i have mentioned above.

Please suggest me.

Thanks in Advance
Mohan.V

Answer

Looks like you need to use merge. Example:

recreating your dataframes:

t1_df<-as.data.frame(matrix(c(1,     "x",      "india",
                              2,     "y",       "usa"), ncol= 3, nrow =2, byrow= T)
                     )
names(t1_df) <- c("id","name","address")

t2_df<-as.data.frame(matrix(c(3,     "a",      "india",
4,     "b",       "usa"), ncol= 3, nrow =2, byrow= T))
names(t2_df) <- c("id","name","address")

Add msg variables. To use merge give both variables a slightly different name (in your case t1_msg and t2_msg)

t1_df$t1_msg <- c("hi","hello")
t2_df$t2_msg <- c("go","bye")

Then use merge to merge the dataframes. Setting all = TRUE will append rows that have no exact match in the other dataframe.

merge(t1_df,t2_df,all = TRUE)

The resulting dataframe looks like this:

  id name address t1_msg t2_msg
1  1    x   india     hi   <NA>
2  2    y     usa  hello   <NA>
3  3    a   india   <NA>     go
4  4    b     usa   <NA>    bye