1

I recently post another question asking how I could create a new data.frame based on a colunm variable. I thought it would fix my problem but I realize now that I was asking the wrong thing. What I mean with my question is, how I can select rows in a constant gap and create a new data.frame with them? Like, if I have:

1   A   B   C
2   D   E   F
3   G   H   I
4   J   K   L
5   M   N   O
6   P   Q   R 

I will want to select the rows that grow in two to two like:

2  D   E   F
4  J   K   L
6  P   Q   R

But actually in my case, I need to select the rows that are groing in 40 to 40 and create a new data.frame with them.

Sorry for another post, but I will be really glad if you guys could help me. I'm a new user of R.

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
Gabriel Lucas
  • 170
  • 1
  • 2
  • 14

2 Answers2

0

It's very easy with the dplyr package.

library(dplyr)
test %>% dplyr::filter(row_number() %% 2 == 0)

Basically, you are calling the row number and selecting only the even ones. If you wanted to go for every 40 rows, you would be doing row_number() %% 40 == 0. If you wanted to start from another row and get every 40 rows, you just need to change the 0 to another number, as the %% operator performs modular divsion.

Kim
  • 4,080
  • 2
  • 30
  • 51
  • Thank you! It's very easy indeed... I was almost given up and selecting the rows by hand haha =) – Gabriel Lucas May 03 '18 at 23:56
  • I think it is entirely possible that you just missed the right search keywords---if you had searched for "every nth row r dataframe", you would have gotten [this post](https://stackoverflow.com/questions/24440258/selecting-multiple-odd-or-even-columns-rows-for-dataframe) and [this post](https://stackoverflow.com/questions/7942519/deleting-every-n-th-row-in-a-dataframe). Cheers! – Kim May 04 '18 at 00:17
0

You can use R base functions if you don't want to load any extra packages:

Option 1

df[seq_len(nrow(df))%%2==0,]

Option 2

subset(df, seq_len(nrow(df))%%2==0)
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138