Deleting every n-th row in a dataframe
Asked Answered
O

3

22

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

Onfre answered 30/10, 2011 at 0:10 Comment(2)
here is one way to do it. df[seq(1, NROW(df), by = n),]Kerf
@Ramnath: df[-seq(n, NROW(df), by = n),] might work betterBackboard
D
39

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)
Diannadianne answered 30/10, 2011 at 0:20 Comment(1)
so df[-rowNumber, ] deletes that particular rowHoptoad
R
15

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

library(dplyr)
df <- data.frame(V1 = seq(26), V2 = letters)

df %>% filter(row_number() %% 2 != 0) ## Delete even-rows
df %>% filter(row_number() %% 2 != 1) ## Delete odd-rows
df %>% 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

Rhineland answered 4/5, 2018 at 0:22 Comment(0)
K
12

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

Kamenskuralski answered 12/4, 2013 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.