Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting a column down by one

Tags:

dataframe

r

Say I have a data.frame that looks like this

 df <- data.frame(AAA = rep(c(NA,sample(1:10, 1)),5),
  BBB = rep(c(NA,sample(1:10, 1)),5),
  CCC = rep(c(sample(1:10, 1),NA),5))

> df 
   AAA BBB CCC
1   NA  NA  10
2    3   7  NA
3   NA  NA  10
4    3   7  NA
5   NA  NA  10
6    3   7  NA
7   NA  NA  10
8    3   7  NA
9   NA  NA  10
10   3   7  NA

I want to shift column CCC down by one so that all the numbers align in a single row, and then delete the rows that contain no data (often every other row - BUT NOT ALWAYS - the pattern might vary through the data.frame.

like image 579
B. Davis Avatar asked Sep 05 '14 14:09

B. Davis


People also ask

How do I move a column down one?

Select the row or column that you want to move or copy. Note: Make sure that you hold down CTRL or SHIFT during the drag-and-drop operation. If you release CTRL or SHIFT before you release the mouse button, you will move the rows or columns instead of copying them.

How do you Shift a column down in Python?

shift() If you want to shift your column or subtract the column value with the previous row value from the DataFrame, you can do it by using the shift() function.


1 Answers

Using dplyr

library(dplyr)
df %>%
mutate(CCC=lag(CCC)) %>%
na.omit()

Or using data.table

library(data.table)
na.omit(setDT(df)[, CCC:=c(NA, CCC[-.N])])
like image 109
akrun Avatar answered Oct 26 '22 23:10

akrun