Deleting every n-th row in a dataframe

2019-01-17 07:24发布

问题:

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

回答1:

You could create a function as follows

Nth.delete<-function(dataframe, n)dataframe[-(seq(n,to=nrow(dataframe),by=n)),]

Let's test it out

DF<-data.frame(A=1:15, B=rnorm(15), C=sample(LETTERS,15))
Nth.delete(DF, 3)


回答2:

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



回答3:

I wish to add the tidyverse style approach to this problem, using the %% operator.

library(dplyr)
df <- data_frame(V1 = seq(1, 26), V2 = letters)
df %>% dplyr::filter(row_number() %% 2 != 0) ## Delete even-rows
df %>% dplyr::filter(row_number() %% 2 != 1) ## Delete odd-rows
df %>% dplyr::filter(row_number() %% 3 != 1) ## Delete every 3rd row starting from 1

You can use the same idea to select every n-th row, of course. See here