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
.
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.
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.
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])])
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