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!
DataFrame. replace() function is used to replace values in column (one value with another value on all columns).
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.
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 .
Your problem simplifies to:
n
elements in a vectorn
values of NA
at the endYou 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With