Ilya Proidakov
Ilya Proidakov

Reputation: 33

Replace all elements in vector with its ordinal number

data frame:

#    V1    V2
1    abc   23
2    bcd   43
3    cde   54
4    def   10

How to replace V1 with its ordinal number?

#    V1    V2
1    1     23
2    2     43
3    3     54
4    4     10

Upvotes: 3

Views: 65

Answers (3)

akrun
akrun

Reputation: 887251

Using data.table

library(data.table)
setDT(dat)[, V1 := .I]

Upvotes: 1

TarJae
TarJae

Reputation: 78947

We could use row_number() from dplyr:

library(dplyr)

df %>% 
  mutate(V1 = row_number())
  V1 V2
1  1 23
2  2 43
3  3 54
4  4 10

Upvotes: 3

Abdur Rohman
Abdur Rohman

Reputation: 2944

Do you mean this?

# Original
dat <- structure(list(V1 = c("abc", "bcd", "cde", "def"), V2 = c(23L, 
43L, 54L, 10L)), row.names = c(NA, -4L), class = "data.frame")
dat
  V1 V2
1 abc 23
2 bcd 43
3 cde 54
4 def 10

# Change V1 with numbers
dat$V1 <- 1:nrow(dat)
  V1 V2
1  1 23
2  2 43
3  3 54
4  4 10

Upvotes: 3

Related Questions