-2

I have a column of ID data (class factor) in the following format: 01-001 etc.

I'd like to extract the first two digits (01) and create a separate column using these digits, ensuring they are numeric.

I did this a few years ago but can't find my old code. Any help would be much appreciated.

Ash
  • 237
  • 2
  • 6
  • 16

1 Answers1

1

Looks like you want substr:

substr(c("01-001", "12-121"), 0, 2)
# [1] "01" "12"

or perhaps

as.numeric(substr(c("01-001", "12-121"), 0, 2))
# [1]  1 12
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
  • 1
    Perfect, that got me going. Thanks Julius. I went with dataframe$variable = substr(dataframe$variable, 0, 2) dataframe$variable = as.numeric(dataframe$variable) – Ash Dec 13 '18 at 11:41