Shifting a column down by one

前端 未结 3 1294
遇见更好的自我
遇见更好的自我 2020-12-06 05:35

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),
  CC         


        
相关标签:
3条回答
  • 2020-12-06 06:02

    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])])
    
    0 讨论(0)
  • 2020-12-06 06:03

    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))), ]
    
    0 讨论(0)
  • 2020-12-06 06:19

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

    df <- na.omit(transform(df, CCC = c(NA, CCC[-nrow(df)])))
    
    0 讨论(0)
提交回复
热议问题