简体   繁体   English

删除数据帧中的每第 n 行

[英]Deleting every n-th row in a dataframe

如何从 R 中的数据框中删除每第 n 行?

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)

If you want to get the each of the nth columns from a data frame or vector etc use modulo subsetting...如果要从数据框或向量等中获取第 n 列中的每一列,请使用模子集...

Select the nth columns by repeating sets here as modulo of 3 (choose nth as you desire)通过在此处重复设置为 3 的模数来选择第 n 列(根据需要选择第 n 个)

> 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..等等...交换 c<-nrow(df) 为子集行..

I wish to add the tidyverse style approach to this problem, using the %% operator.我希望使用%%运算符为这个问题添加tidyverse风格的方法。

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.当然,您可以使用相同的想法来选择每个第 n 行。 See here这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM