Shifting a column down by one

Solution 1:

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

Solution 2:

Use a combination of the very efficient transform and na.omit functions

df <- na.omit(transform(df, CCC = c(NA, CCC[-nrow(df)])))

Solution 3:

You can shift everything down by one with:

df['CCC'] <- c(NA, head(df['CCC'], dim(df)[1] - 1)[[1]])

To delete rows with only NA values, do:

df <- df[apply(df, 1, function(x) !all(is.na(x))), ]