1

I have a simple data frame as follows

x = data.frame(id = seq(1,10),val = seq(1,10))
x
id val
1   1
2   2  
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  10

I want to add 4 more columns. The first 2 are the previous two rows and the next two are the next two rows. For the first two rows and last two rows it needs to write out as NA. How do I accomplish this using cast in the reshape package?

The final output would look like

1 1 NA NA 2 3
2 2 NA 1 3 4
3 3 1 2 4 5
4 4 2 3 5 6

... and so on...

Thanks much in advance

broccoli
  • 4,738
  • 10
  • 42
  • 54
  • 1
    Could you provide us how your expected data.frame should look like so that we can understand much better your problem? – Jilber Urbina Dec 01 '12 at 20:52

2 Answers2

2

After your give the example , I change the solution

 mat <- cbind(dat,
 c(c(NA,NA),head(dat$id,-2)),
 c(c(NA),head(dat$val,-1)),
 c(tail(dat$id,-1),c(NA)),
 c(tail(dat$val,-2),c(NA,NA)))


colnames(mat) <- c('id','val','idp','valp','idn','valn')

   id val idp valp idn valn
1   1   1  NA   NA   2    3
2   2   2  NA    1   3    4
3   3   3   1    2   4    5
4   4   4   2    3   5    6
5   5   5   3    4   6    7
6   6   6   4    5   7    8
7   7   7   5    6   8    9
8   8   8   6    7   9   10
9   9   9   7    8  10   NA
10 10  10   8    9  NA   NA
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • This wouldn't do it. The results appear to be replicated columns. I was looking at the previous 2 values and the following two values making up the 4 new columns. Please refer to the edits I made. – broccoli Dec 01 '12 at 21:03
2

Here is a soluting with sapply. First, choose the relative change for the new columns:

lags <- c(-2, -1, 1, 2)

Create the new columns:

newcols <- sapply(lags,
                  function(l) {
                    tmp <- seq.int(nrow(x)) + l; 
                    x[replace(tmp, tmp < 1 | tmp > nrow(x), NA), "val"]})

Bind together:

cbind(x, newcols)

The result:

   id val  1  2  3  4
1   1   1 NA NA  2  3
2   2   2 NA  1  3  4
3   3   3  1  2  4  5
4   4   4  2  3  5  6
5   5   5  3  4  6  7
6   6   6  4  5  7  8
7   7   7  5  6  8  9
8   8   8  6  7  9 10
9   9   9  7  8 10 NA
10 10  10  8  9 NA NA
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • Thanks for the effort. It didn't work out that well when I was trying to extend it, partly my fault. Found the other solution a bit easier to read. – broccoli Dec 02 '12 at 01:30