I have a dataframe where I want to keep only the odd rows, how would I go about doing that?
Asked
Active
Viewed 650 times
2 Answers
1
We can use a logical index as recycling vectot to return every other row from the original dataset
df1[c(TRUE, FALSE),]

akrun
- 874,273
- 37
- 540
- 662
0
Another option can be testing the module across all rows like this (I have used dummy data). The %%
helps you to test the module with a value. As you want odd rows you can extract the rows which module different from two (1:nrow(d)%%2!=0
). The 1:nrow(d)
is a sequential index to evaluate the rows. Here the code:
#Code
dnew <- d[1:nrow(d)%%2!=0,]
Output:
col1 col2 col3 col4 col5
1 4 4 1 4 Y
3 6 3 3 2 N
5 3 3 3 3 N
7 5 5 5 2 Y
9 6 6 6 6 N
11 2 2 2 2 N
13 0 0 0 0 Y
15 6 6 6 3 N
17 9 1 9 8 N
Some data used:
#Data
d <- structure(list(col1 = c(4, 5, 6, 4, 3, 4, 5, 5, 6, 9, 2, 1, 0,
3, 6, 7, 9), col2 = c(4, 2, 3, 4, 3, 3, 5, 6, 6, 9, 2, 1, 0,
3, 6, 7, 1), col3 = c(1, 2, 3, 4, 3, 4, 5, 5, 6, 9, 2, 1, 0,
3, 6, 7, 9), col4 = c(4, 5, 2, 4, 3, 4, 2, 5, 6, 5, 2, 3, 0,
3, 3, 7, 8), col5 = structure(c(2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L,
1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L), .Label = c("N", "Y"), class = "factor")), class = "data.frame", row.names = c(NA,
-17L))

Duck
- 39,058
- 13
- 42
- 84