Home > Back-end >  Replace all elements in vector with its ordinal number
Replace all elements in vector with its ordinal number

Time:04-24

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

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • r
  • Related