R: shift values ​​in one column of the UP data block

Using sample data, for example:

example=data.frame(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)) 

which is as follows:

  xyz 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8 

I would like to move all the values ​​in the z column up two rows, while the rest of the data frame remains unchanged. The result should look like this:

  xyz 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 

I just found ways to move the column values ​​down or shift the entire data frame.

Any ideas? Thanks!

+8
r dataframe
source share
3 answers

Your problem is simplified:

  • Drop the first n elements in the vector
  • Pad n NA values ​​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) 

Result:

 example xyz 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 
+10
source share

I could not find a good duplicate, so 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)) # xyz # 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 
+1
source share
 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 xyz <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 
0
source share

All Articles