-1

I have a very basic problem. I have a two data frames. The first df1 has 3 columns named col1 and col2

The second df2 has the columns named col3 and col4and col5

I want to create a third data frame with two columns named Attribute and Value in such a way that Attribute is made of the appended value df1$col1 and df2$col3 value is made of the appended values of df1$col2 and df2$col4

Update:

I don't actually the same number of columns for df1 and df2. Notice that I ignored col5 of df2 ( which is irrelevant for my code) This means that

colnames(df1) <- colnames(df2) <- c("attribute", "value")
rbind.data.frame(df1, df2)

is not working for me.

How can I achieve this result?

  • No I don't wont to concatenate the column. I want to append the second at the bottom of the second –  Oct 14 '16 at 12:43
  • 1
    Or [Simplest way to get rbind to ignore column names](http://stackoverflow.com/questions/19297475/simplest-way-to-get-rbind-to-ignore-column-names) – Ronak Shah Oct 14 '16 at 12:50
  • sorry, I didn't show on the question for the sake of simplicity but I actually have different number of columns for `df1` and `df2` –  Oct 14 '16 at 12:57

2 Answers2

0

df.n <-NULL df.n$a<-rbind(df1$col1, df2$col3) df.n$b<-rbind(df1$col2,df2$col4)

This requires that col1+col3 has the same number of rows as col2+col4

Daniel Winkler
  • 487
  • 3
  • 11
0

If you want to append df2 to df1 the data frames need to have the same columns names.

Otherwise R will complain that the names do not match. Therefore, you have to make the column names the same.

You can achieve this by using the third statement in the following snipped. Then you can simply rbind them to create df3.

df1 <- data.frame(col1=1, col2=2)
df2 <- data.frame(col3=1, col2=4) 

colnames(df2) <- colnames(df1)

df3 <- rbind(df1, df2)
PhillipD
  • 1,797
  • 1
  • 13
  • 23
  • my columns have different names –  Oct 14 '16 at 12:46
  • @communitywiki that's why I use the colname statement. df3 will have - in this case - column names col1 and col2. – PhillipD Oct 14 '16 at 12:48
  • I am sorry I corrected my question. I didn't show on the question for the sake of simplicity but I actually have different number of columns for df1 and df2 –  Oct 14 '16 at 12:59
  • @communitywiki then you might have a look at this question: http://stackoverflow.com/questions/3402371/combine-two-data-frames-by-rows-rbind-when-they-have-different-sets-of-columns – PhillipD Oct 14 '16 at 13:12