-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?

3
  • No I don't wont to concatenate the column. I want to append the second at the bottom of the second Commented Oct 14, 2016 at 12:43
  • 1
    Or Simplest way to get rbind to ignore column names Commented Oct 14, 2016 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 Commented Oct 14, 2016 at 12:57

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

my columns have different names
@communitywiki that's why I use the colname statement. df3 will have - in this case - column names col1 and col2.
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
@communitywiki then you might have a look at this question: stackoverflow.com/questions/3402371/…
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

2 Comments

Error: unexpected numeric constant in "df.n$1"
sorry colnames cannot be numbers I edited