Create an ID (row number) column

后端 未结 8 1960
我在风中等你
我在风中等你 2020-11-29 02:06

I need to create a column with unique ID, basically add the row number as an own column. My current data frame looks like this:

   V1  V2
1  23  45
2  45  4         


        
相关标签:
8条回答
  • 2020-11-29 02:34

    data.table solution

    Easier syntax and much faster

    library(data.table)
    
    dt <- data.table(V1=c(23, 45, 56), V2=c(45, 45, 67))
    
    setnames(dt, c("V2", "V3")) # changing column names
    dt[, V1 := .I] # Adding ID column
    
    0 讨论(0)
  • 2020-11-29 02:35

    If you're starting without named rows in your df, the tidy way is:

    df %>% 
      mutate(id = row_number()) %>% 
      select(id, everything())
    
    0 讨论(0)
提交回复
热议问题