Reputation: 2319
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
Upvotes: 3
Views: 272
Reputation: 39858
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
Upvotes: 4