Emily
Emily

Reputation: 211

Adding a column with consecutive numbers in R

I apologize if this question is abhorrently simple, but I'm looking for a way to just add a column of consecutive integers to a data frame (if my data frame has 200 observations, for example, starting with 1 for the first observation, and ending with 200 on the last one).

How can I do this?

Upvotes: 21

Views: 80512

Answers (3)

Ilya V. Schurov
Ilya V. Schurov

Reputation: 8067

Probably, function tibble::rowid_to_column is what you need if you are using tidyverse ecosystem.

library(tidyverse)
dat <- tibble(x=c(10, 20, 30), 
              y=c('alpha', 'beta', 'gamma'))
dat %>% rowid_to_column(var='observation')

# A tibble: 3 x 3
  observation     x y    
        <int> <dbl> <chr>
1           1    10 alpha
2           2    20 beta 
3           3    30 gamma

Upvotes: 2

Joe
Joe

Reputation: 8631

Or use dplyr.

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

You might want it to be the first column of df.

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

Upvotes: 15

Alex
Alex

Reputation: 504

For a dataframe (df) you could use

df$observation <- 1:nrow(df) 

but if you have a matrix you would rather want to use

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

as using the first option will transform your data into a list.

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

Upvotes: 25

Related Questions