Adding a sequential column to R

I'm sorry if this question is disgustingly simple, but I'm looking for a way to just add a column of consecutive integers to the dataframe (assuming there are 200 observations in my dataframe, for example starting at 1 for the first observation and ending at 200 for the last).

How can i do this?

+3


source to share


2 answers


For dataframe (df) you can use

df$observation <- 1:nrow(df) 

      

but if you have a matrix you prefer to use



ma <- cbind(ma, "observation"=1:nrow(ma)) 

      

as using the first parameter will convert your data to a list.

Source: http://r.789695.n4.nabble.com/adding-column-of-ordered-numbers-to-matrix-td2250454.html

+7


source


Or use dplyr

.

library(dplyr)
df %>% mutate(observation = 1:n())

      



You might want this to be the first column df

.

df %>% mutate(observation = 1:n()) %>% select(observation, everything())

      

+1


source







All Articles