Home > Software engineering >  alphanumeric to increasing numbers in R
alphanumeric to increasing numbers in R

Time:05-25

I have a table in R with a column of ID's like: '1A', '2A', '1B', '2B', etc.

I would like to convert them to numbers such as: 1, 2, 3, 4, etc.

I would appreciate any suggestion. Thanks!

CodePudding user response:

df <- data.frame(list(
  IDs=c('1A', '2A', '1B', '2B'),
  vals=c(8,8,8,8)
))

# assuming that the IDs are in sequential order
# replace the IDs vector with a sequence of numbers
# starting at 1 and ending at the length of the data frame
df$IDs <- seq(1,nrow(df))


  IDs vals
1   1    8
2   2    8
3   3    8
4   4    8

The tidyverse solution would be to use row_number

library(tidyverse)
df <- df %>% mutate(IDs = row_number())

CodePudding user response:

Another way is to convert to a factor, and then to numbers. that way there is no assumptions of sequential order.

df <- data.frame(list(
  IDs=c('1A', '2A', '1B', '2B'),
  vals=c(8,8,8,8)
))

df$IDs <- as.numeric(as.factor(df$IDs))
  • Related