Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift values in single column of dataframe up

Tags:

dataframe

r

Using example data like this:

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 looks like this:

    x   y   z
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 shift all values in the z column upwards by two rows while the rest of the dataframe remains unchanged. The result should look like this:

    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

I only found ways to move the values of a column down, or a shifting of the whole dataframe.

Any ideas? Thanks!

like image 945
Anne Avatar asked Sep 23 '14 12:09

Anne


People also ask

How do I change the values in a column in a DataFrame?

DataFrame. replace() function is used to replace values in column (one value with another value on all columns).

What does shift () do in pandas?

shift() function Shift index by desired number of periods with an optional time freq. This function takes a scalar parameter called the period, which represents the number of shifts to be made over the desired axis. This function is very helpful when dealing with time-series data.

How do you move values in pandas?

Shifting values with periodsPandas shift() shift index by the desired number of periods. The simplest call should have an argument periods (It defaults to 1 ) and it represents the number of shifts for the desired axis . And by default, it is shifting values vertically along the axis 0 .


2 Answers

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
like image 145
Andrie Avatar answered Sep 23 '22 09:09

Andrie


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  
like image 42
Nettle Avatar answered Sep 19 '22 09:09

Nettle