0

Suppose I have a data frame containing 192 rows and I want to select 12 rows alternatively.

i.e. select first 12 rows, then select 25 to 36 rows, then select 49 to 60 rows.

How to do that in R?

989
  • 12,579
  • 5
  • 31
  • 53
Pramod
  • 79
  • 6
  • 1
    Possible duplicate of [Selecting multiple parts of a list](https://stackoverflow.com/questions/14794602/selecting-multiple-parts-of-a-list), Also [Create a sequence of indexes by block](https://stackoverflow.com/questions/42954495/create-a-sequence-of-indexes-by-block/) – Ronak Shah Jul 03 '17 at 07:09
  • Please read how to ask - https://stackoverflow.com/help/how-to-ask/. *Search and research*. Questions similar to like this have often been asked. Search for example "[r] select rows in dataframe" and this will often help you give you clues. see [1](https://stackoverflow.com/a/21915056/4606130), for more complex work [2](https://stackoverflow.com/q/11612235/4606130). – micstr Jul 03 '17 at 07:10

2 Answers2

2

Using the iris data as an example.

Simply use iris[1:12,] for the first 12 rows:

# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1           5.1         3.5          1.4         0.2  setosa
#2           4.9         3.0          1.4         0.2  setosa
#3           4.7         3.2          1.3         0.2  setosa
#4           4.6         3.1          1.5         0.2  setosa
#5           5.0         3.6          1.4         0.2  setosa
#6           5.4         3.9          1.7         0.4  setosa
#7           4.6         3.4          1.4         0.3  setosa
#8           5.0         3.4          1.5         0.2  setosa
#9           4.4         2.9          1.4         0.2  setosa
#10          4.9         3.1          1.5         0.1  setosa
#11          5.4         3.7          1.5         0.2  setosa
#12          4.8         3.4          1.6         0.2  setosa

iris[25:36,] for rows 25 to 36, and so on.

Note that iris will be swapped to the name of your data frame. The comma is used to select either rows or columns. Thus, iris[,1:3] would select the first 3 columns of the data frame.

J.Con
  • 4,101
  • 4
  • 36
  • 64
  • it will be more manual coding .. can you put in loop and extract the data from dataframe – Pramod Jul 03 '17 at 06:57
  • Do you mean you would like a loop that does something to the first 12 rows, then something different to rows 25-36, etc? – J.Con Jul 03 '17 at 06:58
  • no .. i just want to extract 12 rows alternatively which should be done by loop because the data frame is big – Pramod Jul 03 '17 at 07:05
1

You could do this vectorized using recycling technique in R (df is your data frame):

df[rep(c(TRUE, FALSE), each = 12),]
989
  • 12,579
  • 5
  • 31
  • 53