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?
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?
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.
You could do this vectorized using recycling technique in R (df
is your data frame):
df[rep(c(TRUE, FALSE), each = 12),]