Home > Enterprise >  How can I rbind multiple single-value rows to my data.frame?
How can I rbind multiple single-value rows to my data.frame?

Time:10-04

The following works as expected:

A <- data.frame(c(1, 2, 3))
B <- data.frame(4, 5, 6)
cbind(A, B)
  c.1..2..3. X4 X5 X6
1          1  4  5  6
2          2  4  5  6
3          3  4  5  6

Now I am doing the transpose with rbind:

At <- data.frame(1, 2, 3)
Bt <- data.frame(c(4, 5, 6))
rbind(At, Bt)

and this is not working:

Error in rbind(deparse.level, ...) : numbers of columns of arguments do not match

Interstingly, both cbind and rbind support the following:

cbind(A, 4, 5, 6)
  c.1..2..3. 4 5 6
1          1 4 5 6
2          2 4 5 6
3          3 4 5 6

rbind(At, 4, 5, 6)
  X1 X2 X3
1  1  2  3
2  4  4  4
3  5  5  5
4  6  6  6

where the latter is what I am expecting from rbind(At, Bt).

How can I get it?

Edit: Some context: I have a large call rbind(A1t, ..., Bt, ..., A2t), so I would prefer an answer which processes Bt in a way such that I don't have to modify the sequence of parameters of rbind. (I would be fine with replacing rbind by an alternative.)

Interestingly, the implementations of cbind and rbind are 100% analogous, so I wonder why the two behave differently anyway:

https://github.com/wch/r-source/blob/79298c4/src/library/methods/R/cbind.R#L35-L125

https://github.com/wch/r-source/blob/79298c4/src/library/methods/R/rbind.R#L24-L114

CodePudding user response:

You can use do.call to achieve the same output as rbind(At, 4, 5, 6).

At <- data.frame(col1 = 1, col2 = 2, col3 = 3)
Bt <- data.frame(col1 = c(4, 5, 6))

do.call(function(...) rbind(At, ...), as.list(Bt$col1))

#  col1 col2 col3
#1    1    2    3
#2    4    4    4
#3    5    5    5
#4    6    6    6

Since the length of Bt$col1 can be variable I have used ... as argument to the function.

CodePudding user response:

rbind(At, Bt)

In this case you create 2 data.frames:

At <- data.frame(1, 2, 3)
Bt <- data.frame(c(4, 5, 6))

str(At)
'data.frame':   1 obs. of  3 variables:
 $ X1: num 1
 $ X2: num 2
 $ X3: num 3

str(Bt)
'data.frame':   3 obs. of  1 variable:
 $ c.4..5..6.: num  4 5 6

rbind requires the same columns names, also the number of columns differs.

rbind(At, 4, 5, 6)

In that case R "completes" each row repeating each number for the entire row, and giving an automatic name, e.g., X1. Would be the same as

rbind(
  At,
  c(4,4,4),
  c(5,5,5),
  c(6,6,6)
  )

or

rbind(
  At,
  data.frame(X1 = 4,X2 = 4,X3 = 4),
  data.frame(X1 = 5,X2 = 5,X3 = 5),
  data.frame(X1 = 6,X2 = 6,X3 = 6)
  )
  • Related