rdataframepipenames

Resequencing the rows of an R data frame using the native pipe


Minimal Example

df <- data.frame(x = c(10, NA, 30, 40, 50),                  
                  y = c(10, 20, NA, 40, 50))

df <- df |>
       na.omit() |>
       `colnames<-`(c("You", "Me")) 
>df
      You Me
    1  10 10
    4  40 40
    5  50 50

I would like to resequence the rows of the filtered data frame to go from 1 to the number of rows. I know I can do this by writing

> rownames(df) <- NULL
> df
  You Me
1  10 10
2  40 40
3  50 50

How can I achieve the same end using the base R pipe just as I have done for colnames?

Many thanks in advance

Thomas Philips


Solution

  • It's the same for rownames, i.e. you can do

    df <- df |>
      na.omit() |>
      `colnames<-`(c("You", "Me")) |> 
      `rownames<-`(NULL)
    
    df
    #>   You Me
    #> 1  10 10
    #> 2  40 40
    #> 3  50 50
    

    Created on 2025-04-30 with reprex v2.1.1`