1

Suppose there is a data frame with a fixed number of row, for example

a <- as.data.frame(c(1:7))

And there is another vector with fewer (or bigger) number of row:

b <- c(1:4)

Then it is not possible to add b as new column into a:

a <- cbind(a, b)

Here is the output:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 7, 4

Where the following result is expected:

1      1      1
2      2      2
3      3      3
4      4      4
5      5     NA
6      6     NA
7      7     NA
Mostafa Barmshory
  • 1,849
  • 24
  • 39

2 Answers2

5

We can do this easily with cbind.fill from rowr

rowr::cbind.fill(a, b, fill = NA)
akrun
  • 874,273
  • 37
  • 540
  • 662
3

You can use:

a <- 1:7
b <- 1:4
n <- max(length(a), length(b))
length(a) <- n                      
length(b) <- n

df <- data.frame(cbind(a, b))
Constantinos
  • 1,327
  • 7
  • 17
  • 2
    The only part that you haven't copy/pasted from the dupe (`data.frame(cbind(a, b))`) is a very bad practice for data frames. – David Arenburg May 25 '17 at 12:10
  • Wow!! Believe it or not, I actually wrote it down from scratch! When I dont know an R function that does something, I usuallly break it down in smaller chunks and try to figure it out in base R. I didn't like `as.data.frame(c(1:7))` so I used `1:7` whereas " ... fewer (or bigger) number of row (sic)" led me to compare the lengths. Yes, it was a quick fix and probably very inefficient (but maybe not important for the lengths the poster asked for), but I've never claimed to be an expert so perhaps I'm a dupe, indeed! – Constantinos May 25 '17 at 13:11