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?


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.




Or use dplyr


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


You might want this to be the first column df


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




All Articles