Home > Enterprise >  How to order rows in dataframe with a new piping in r?
How to order rows in dataframe with a new piping in r?

Time:07-28

I want to use a new R pipe |> for the script like this:

df <- data.frame (letter=c(rep("a",3), rep("b",3), rep("c",2)),
                    number = c(1,3,4,7,6,2,5,8))
df <- df[which(df$letter !="c"),]
df <- df[order(df$number),]

I tried this

df <- data.frame (letter=c(rep("a",3), rep("b",3), rep("c",2)),
                  number = c(1,3,4,7,6,2,5,8)) |>
  df[which(df$letter !="c"),] |>
  df[order(df$number),]

But got an error

Error: function '[' not supported in RHS call of a pipe

How to use |> in this case to filter and order rows in a dataframe?

CodePudding user response:

library(dplyr)

df |> 
  filter(letter != "c") |>
  arrange(number)

  letter number
1      a      1
6      b      2
2      a      3
3      a      4
5      b      6
4      b      7

CodePudding user response:

You can use [ as a function then apply |> operator as follows

df <- df |> (\(x)`[`(x,which(df$letter !="c") ,))()

df |> (\(x)`[`(x,order(df$number) ,))()

  • output
  letter number
1      a      1
6      b      2
2      a      3
3      a      4
5      b      6
4      b      7
  •  Tags:  
  • r
  • Related