1

Given some data

hello <- c('13.txt','12.txt','14.txt')

I want to just take the numbers and convert to numeric, i.e. remove the .txt

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
luke123
  • 631
  • 3
  • 9
  • 15

4 Answers4

7

You want file_path_sans_ext from the tools package

library(tools)
hello <- c('13.txt','12.txt','14.txt')
file_path_sans_ext(hello)
## [1] "13" "12" "14"
mnel
  • 113,303
  • 27
  • 265
  • 254
  • Thanks. I can't install that package on my current setup for some reason, is there another way using basic R syntax? – luke123 Mar 20 '13 at 02:05
  • @luke123 -- `tools` is part of the standard R distribution. You shouldn't have to install it, just call library – mnel Mar 20 '13 at 02:06
  • @mnel recently discovered this one myself and have loved it just for these situations. +1 – Tyler Rinker Mar 20 '13 at 02:49
  • reputation aside, I'm totally saddened that a solution that requires loading a special package (a dependency) gets more upvotes than the pure base-R solutions. – ndoogan Jul 13 '18 at 22:13
5

You can do this with regular expressions using the function gsub on the "hello" object in your original post.

hello <- c('13.txt','12.txt','14.txt')
as.numeric(gsub("([0-9]+).*","\\1",hello))
#[1] 13 12 14
ndoogan
  • 1,925
  • 12
  • 15
3

Another regex solution

hello <- c("13.txt", "12.txt", "14.txt")
as.numeric(regmatches(hello, gregexpr("[0-9]+", hello)))
## [1] 13 12 14
CHP
  • 16,981
  • 4
  • 38
  • 57
1

If you know your extensions are all .txt then you can use substr()

> hello <- c('13.txt','12.txt','14.txt')
> as.numeric(substr(hello, 1, nchar(hello) - 3))
#[1] 13 12 14
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453