Adding a column with consecutive numbers in R

后端 未结 3 1521
不思量自难忘°
不思量自难忘° 2021-02-13 14:14

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 observation

相关标签:
3条回答
  • 2021-02-13 14:47

    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
    
    0 讨论(0)
  • 2021-02-13 14:56

    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

    0 讨论(0)
  • 2021-02-13 14:58

    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())
    
    0 讨论(0)
提交回复
热议问题