Shift values in single column of dataframe up

Solution 1:

Your problem simplifies to:

  • Drop the first n elements in a vector
  • Pad n values of NA at the end

You can do this with a simple function:

shift <- function(x, n){
  c(x[-(seq(n))], rep(NA, n))
}

example$z <- shift(example$z, 2)

The result:

example
  x y  z
1 1 1  3
2 2 2  4
3 3 3  5
4 4 4  6
5 5 5  7
6 6 6  8
7 7 7 NA
8 8 8 NA

Solution 2:

example = tibble(x=c(1,2,3,4,5,6,7,8), 
                   y=c(1,2,3,4,5,6,7,8), 
                   z=c(1,2,3,4,5,6,7,8))

example %>% mutate_at(c("z"), funs(lead), n = 2 )

# A tibble: 8 x 3
      x     y     z
  <dbl> <dbl> <dbl>
1  1.00  1.00  3.00
2  2.00  2.00  4.00
3  3.00  3.00  5.00
4  4.00  4.00  6.00
5  5.00  5.00  7.00
6  6.00  6.00  8.00
7  7.00  7.00 NA   
8  8.00  8.00 NA  

Solution 3:

I couldn't find a good duplicate, so here's another solution using length<-

shift2 <- function(x, n) `length<-`(tail(x, -n), length(x)) 
# or just shift2 <- function(x, n) c(tail(x, -n), rep(NA, n))
transform(example, z = shift2(z, 2))   
#   x y  z
# 1 1 1  3
# 2 2 2  4
# 3 3 3  5
# 4 4 4  6
# 5 5 5  7
# 6 6 6  8
# 7 7 7 NA
# 8 8 8 NA