Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

row numbers in tibble after subsetting - R programming

How to display the row number after sub setting tibble .

Here is the example , first i am sub setting the classic data frame , results show me the observations with the row number (106,118,119,123 ... )

Below when i am sub setting tibble , it is not giving the observation rownumbers, instead it shows 1,2,3,4.....

Anyway to i can make tibble show the observation row number after sub setting?

> iris[iris$Sepal.Length >7.4,]
    Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
106          7.6         3.0          6.6         2.1 virginica
118          7.7         3.8          6.7         2.2 virginica
119          7.7         2.6          6.9         2.3 virginica
123          7.7         2.8          6.7         2.0 virginica
132          7.9         3.8          6.4         2.0 virginica
136          7.7         3.0          6.1         2.3 virginica
> iris_tibble=as.tibble(iris)
> iris_tibble[iris_tibble$Sepal.Length >7.4,]
# A tibble: 6 x 5
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species  
         <dbl>       <dbl>        <dbl>       <dbl> <fct>    
1          7.6         3            6.6         2.1 virginica
2          7.7         3.8          6.7         2.2 virginica
3          7.7         2.6          6.9         2.3 virginica
4          7.7         2.8          6.7         2   virginica
5          7.9         3.8          6.4         2   virginica
6          7.7         3            6.1         2.3 virginica
like image 354
Prabha A Avatar asked Oct 24 '25 16:10

Prabha A


2 Answers

You can create a column with row names and then do the filtering/subsetting.

Using dplyr:

iris %>%
  mutate(row_name = row_number()) 

Or using tibble:

rowid_to_column(iris, "row_name")
like image 187
tmfmnk Avatar answered Oct 26 '25 05:10

tmfmnk


I don't think data.table supports row names. But you could do

iris <- iris %>%
    rownames_to_column() %>%
    as.tibble(iris)

Then you should have a column that has the row numbers that will maintain when filtered.

like image 37
user3304359 Avatar answered Oct 26 '25 07:10

user3304359