Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting every n-th row in a dataframe

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

like image 923
Yktula Avatar asked Oct 30 '11 00:10

Yktula


People also ask

How do you remove nth row in a data frame?

To delete a row from a DataFrame, use the drop() method and set the index label as the parameter.

How do you take every nth row in Python?

To select every nth row of a DataFrame - we will use the slicing method. Slicing in pandas DataFrame is similar to slicing a list or a string in python. Suppose we want every 2nd row of DataFrame we will use slicing in which we will define 2 after two :: (colons).

How do I delete multiple rows in a data frame?

To delete rows and columns from DataFrames, Pandas uses the “drop” function. To delete a column, or multiple columns, use the name of the column(s), and specify the “axis” as 1. Alternatively, as in the example below, the 'columns' parameter has been added in Pandas which cuts out the need for 'axis'.

How do I delete last 10 rows in a DataFrame?

We can remove the last n rows using the drop() method. drop() method gets an inplace argument which takes a boolean value. If inplace attribute is set to True then the dataframe gets updated with the new value of dataframe (dataframe with last n rows removed).


2 Answers

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)
like image 71
Tyler Rinker Avatar answered Oct 14 '22 19:10

Tyler Rinker


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

like image 44
Kim Avatar answered Oct 14 '22 19:10

Kim