'R:How to select the amount of data in a dataset by a given variable

Let's take dataset iris and there is static value g=101. Iris dataset has 150 value. How to select exactly as many observations in the iris dataset as indicated in the variable g starting from the very first observation? As final result will be iris dataset ,but with 101 obs.

r


Solution 1:[1]

We can use seq_len on 'g' and use as row index

g <- 101
iris_sub <- iris[seq_len(g),]

-output

> dim(iris_sub)
[1] 101   5

Solution 2:[2]

in a dataframe, isn't this the basic df[1: n,] will select all records from 1 to N and all columns if none is specified. (If you have modified the data - say sorted etc and saved, it will show saved result]

so iris[1:g,] will itself work. No need for anything more with g <- 101

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akrun
Solution 2 anuanand