I don't understand this example from the dplyr help for row_numbr() using ?row_number().
library(dplyr)
x <- c(5, 1, 3, 2, 2, NA)
row_number(x)
[1] 5 1 4 2 3 NA
Why is the result not c(1, 2, 3, 4, 5, 6)? With mtcars:
mtcars %>%
select(mpg, cyl) %>%
mutate(row_num = row_number()) %>%
head()
which just gives the row number:
mpg cyl row_num
1 21.0 6 1
2 21.0 6 2
3 22.8 4 3
4 21.4 6 4
5 18.7 8 5
6 18.1 6 6
If you look at help("row_number"), then you can find that:
row_number(): equivalent to rank(ties.method = "first")
Moreover, as you vector contains also NA, it should be noted that:
x (is) a vector of values to rank. Missing values are left as is. If you want to treat them as the smallest or largest values, replace with Inf or -Inf before ranking.
What can be used instead is:
seq_along(x)
[1] 1 2 3 4 5 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With