1

I have a data frame which has 25 weeks data on sales. I have computed a lagged moving average. Now, say x <- c(1,2,3,4) and moving average y <- c(Nan,1,1.5,2,2.5).

If I use z <- data.frame(x,y) it's giving me error as the dimensions are not matching. Is there any way to join them as a data frame by inserting an NA value at the end of the x column? '

Is the same thing possible when x is a data frame with n rows, m columns and I want to append a column of length (m+1) to the right of it?

Luke Peterson
  • 8,584
  • 8
  • 45
  • 46

3 Answers3

4

Yet another way of doing it

 data.frame(x[1:length(y)], y)

If x is a data frame, you can use

data.frame(x[1:length(y), ], y)
konvas
  • 14,126
  • 2
  • 40
  • 46
1

You could do this

> lst <- list(x = x, y = y)
> m <- max(sapply(lst, length))
> as.data.frame(lapply(lst, function(x){ length(x) <- m; x }))
#     x   y
# 1   1 NaN
# 2   2 1.0
# 3   3 1.5
# 4   4 2.0
# 5  NA 2.5

In response to your comment, if x is a matrix and y is a vector, it would depend on the number of columns in x. But for this example

cbind(append(x, rep(NA, length(y)-length(x))), y)

If x has multiple columns, you could use some variety of

apply(x, 2, append, NA)

But again, it depends on what's in the columns and what's in y

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
1

May be this also helps:

x<- 1:4
x1 <- matrix(1:8,ncol=2)
y <- c(NaN,1,1.5,2,2.5)


do.call(`merge`, c(list(x,y),by=0,all=TRUE))[,-1]
#    x   y
#  1  1 NaN
#  2  2 1.0
#  3  3 1.5
#  4  4 2.0
#  5 NA 2.5

do.call(`merge`, c(list(x1,y),by=0,all=TRUE))[,-1]
 # V1 V2   y
#1  1  5 NaN
#2  2  6 1.0
#3  3  7 1.5
#4  4  8 2.0
#5 NA NA 2.5
akrun
  • 874,273
  • 37
  • 540
  • 662