Working on a 4 rows data.frame object with dplyr, I want to created a new "id" column combining a prefix string and a sequence of values.
What I expected:
columnA|columnB|columnC|id
data data data id-1
data data data id-2
data data data id-3
data data data id-4
What I tried:
library (dplyr)
y <- x %>%
mutate (id = "id- " & seq(from = 1, to =4, by = 1))
%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. It is defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).
In R programming, the mutate function is used to create a new variable from a data set. In order to use the function, we need to install the dplyr package, which is an add-on to R that includes a host of cool functions for selecting, filtering, grouping, and arranging data.
Either:
x %>% mutate(id = paste0('id-', 1:4))
or:
x %>% mutate(id = paste0('id-', row_number()))
or:
x %>% mutate(id = paste0('id-', 1:n()))
gives you what you want:
columnA columnB columnC id
1 data data data id-1
2 data data data id-2
3 data data data id-3
4 data data data id-4
Off course this can also be accomplished easily in base R:
x$id <- paste0('id-', 1:nrow(x))
It is better not to use row.names
because they are not always numbers (see for example row.names(mtcars)
).
Or using the data.table
package:
library(data.table)
setDT(x)[, id := paste0('id-',.I)]
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