1

Problem:

I am trying to combine the columns of two vectors with different lengths and starting dates (think stock prices) and want to cut off the excess from the longest while matching the length of the shortest. Any help would be appreciated!

What I have tried so far:

combinedcolumns<-cbind(A$Col,B$Col[(length(B$Col)-length(A$Col)):length(B$Col)])

Results:

I am able to bind the two columns and get correct values for A, but I get the same value for B across the entire length of combinedcolumns.

Thanks in advance!

nicola
  • 24,005
  • 3
  • 35
  • 56
Dustin
  • 11
  • 1
  • 1
    Do all of the dates in the shorter column have matching dates in the longer column? If so, it would probably be better to `merge` by date. For example, assuming `A` is the shorter one and that both data frames have a column called `date`: `merge(A, B, by="date", all.x=TRUE)`. – eipi10 Mar 31 '18 at 19:29

1 Answers1

0

One way would be to extend the shorter column by filling it with NAs (or anything else basically), i.e.

lmax <- max(c(length(A$col1), length(B$col2))) # determining which column is longer / shorter
lmin <- max(c(length(A$col1), length(B$col2)))
col2change <- which(c(length(A$col1), length(B$col2)) == lmin)
newcol <- rep(NA, lmax) # creating a vector of length lmax filled with NAs
newcol[1:lmin] <- ifelse(col2change == 1,          # adding the data of the shorter col
                         A$col1,
                         B$col2)
combinedcolumns <- ifelse(col2change == 1,
                         cbind(A$col1, newcol),
                         cbind(newcol, B$col2))
niko
  • 5,253
  • 1
  • 12
  • 32