I have a very simple dataset such as:
datfra <- data.frame(ID = c(2, 3, 5, 4, 1),
Species = c("bluewhale", "bluewhale","bndolphin","bluewhale","whalesp"))
Looking:
> datfra
ID Species
1 2 bluewhale
2 3 bluewhale
3 5 bndolphin
4 4 bluewhale
5 1 whalesp
I would like to add a 3rd column, numbering the rows, but starting from a certain specific number, something like:
strartingfrom <- 15
datfra <- datfra %>% arrange(ID) %>% mutate(newID = row_number(from=strartingfrom))
Obviously the from
inside row_number
doesn't work. Anyone has an elegant way to number rows starting at a different number to 1?
Should look like:
newID ID Species
1 16 1 whalesp
2 17 2 bluewhale
3 18 3 bluewhale
4 19 4 bluewhale
5 20 5 bndolphin
[EDIT]
I got it solved just trying a simmple approach:
datfra <- datfra %>% arrange(ID) %>% mutate(newID = strartingfrom row_number())
CodePudding user response:
You can directly try this:
datfra <- datfra %>%
arrange(ID) %>%
mutate(newID = strartingfrom:(strartingfrom nrow(datfra) - 1))
Or make a function:
newID_row_number <- function(dt, start_from, by_id="ID") {
dt <- dt %>%
arrange(!!as.name(by_id)) %>%
mutate(newID = start_from:(start_from nrow(dt)-1))
return(dt)
}
strartingfrom <- 15
datfra <- newID_row_number(datfra, strartingfrom)
CodePudding user response:
May be you can use this :
start = 10
datfra$newID = seq(start, nrow(datfra) start-1)
CodePudding user response:
Use `:`()
and order()
.
i <- 15 ## define start
transform(datfra[order(datfra$ID), ], new=15:(15 nrow(datfra) - 1))
# ID Species new
# 5 1 whalesp 15
# 1 2 bluewhale 16
# 2 3 bluewhale 17
# 4 4 bluewhale 18
# 3 5 bndolphin 19