Demlovat
Demlovat

Reputation: 37

Merge text columns from different datafrm

In one dataframe I have 2 columns and one column into a second df.

I would like to take all rows from thee three columns into one column.

Merge like test <- merge(df1$col1,df1$col2,df2$col2) is not the right solution.

Any idea which is the right one?

Upvotes: 0

Views: 45

Answers (2)

Miha
Miha

Reputation: 2884

I think you need rbindlist from data.table()package

So first I created some data as an example:

# Three different vectors that will be converted to data frame with single column
a <- as.data.frame(c(1:3))
b <- as.data.frame(LETTERS[seq(1:4)])
c <- as.data.frame(1:10)

# Then I've used function rbindlist to row bind
rbindlist(list(a, b, c))

# And the output (one column with total number 17)

    c(1:3)
 1:      1
 2:      2
 3:      3
 4:      A
 5:      B
 6:      C
 7:      D
 8:      1
 9:      2
10:      3
11:      4
12:      5
13:      6
14:      7
15:      8
16:      9
17:     10

UPDATE

rbindlist() works with list, data.frames and data.tables, not with list of atomic types. So you need to edit your code like this rbindlist(list(df1["col1"],df1["col2"],df2["col2"]))

Upvotes: 1

stevec
stevec

Reputation: 52518

In order to rbind the columns, they'll need to have the same number of rows:

df2$col2 <- NA # Ensures ncol(df2) == ncol(df1)
test <- rbind(df1, df2)

Upvotes: 1

Related Questions