Deleting every n-th row in a dataframe

后端 未结 3 1364
清酒与你
清酒与你 2020-12-01 08:08

How can I delete every n-th row from a dataframe in R?

3条回答
  •  情深已故
    2020-12-01 08:57

    If you want to get the each of the nth columns from a data frame or vector etc use modulo subsetting...

    Select the nth columns by repeating sets here as modulo of 3 (choose nth as you desire)

    > x <- c(1,2,3,4,5,6)
    > d <- rbind(x,x,x)
    > df <- as.data.frame(d, row.names=T)
    > c <- 1:ncol(df)
    > c
    [1] 1 2 3 4 5 6
    c%%3   ### nth cycle, here every 3
    [1] 1 2 0 1 2 0
    
    #select the every 3rd column of every 3
    > df[, c%%3==0]  
      V3 V6
    1  3  6
    2  3  6
    3  3  6
    
    #every first column of every 3
    > df[, c%%3==1]
      V1 V4
    1  1  4
    2  1  4
    3  1  4
    
    #every 2nd column of every 3
    > df[, c%%3==2]
      V2 V5
    1  2  5
    2  2  5
    3  2  5
    
    
    #drop the 3rd columns  
    > df[, !(c%%3==0)]
      V1 V2 V4 V5
    1  1  2  4  5
    2  1  2  4  5
    3  1  2  4  5
    

    etc... swap c<-nrow(df) for subsetting rows..

提交回复
热议问题