-3

I am looking for a code to remove the characters from an alphanumeric vector of a data frame. This my data column below:

F9667968CU
67968PX11
3666SP
6SPF10
2323DL1
23DVL10
2016PP07

And this is the code I have used:

for(i in 1: length(rownames(testsample)))
{
    testsample$column1[i]<-gsub("[a-zA-Z]","",testsample$column1[i])
}

And below is the output I am expecting:

9667968
6796811
3666
610
23231
2310
201607
Jaap
  • 81,064
  • 34
  • 182
  • 193
Monsta
  • 59
  • 3
  • 7
  • 4
    really? [First google hit](http://stackoverflow.com/questions/17009628/extracting-numbers-from-string-in-r), [second](http://stackoverflow.com/questions/15451251/extract-numeric-part-of-strings-of-mixed-numbers-and-characters-in-r), [third](http://stackoverflow.com/questions/14543627/extracting-numbers-from-vectors-of-strings) – Sotos Sep 21 '16 at 10:06
  • 1
    `gsub` is vectorised you don't need a for loop, `testsample$column1 <- gsub("[a-zA-Z]","",testsample$column1)` should work – Cath Sep 21 '16 at 10:06

1 Answers1

2

Try this:

df
         col
1 F9667968CU
2  67968PX11
3     3666SP
4     6SPF10
5    2323DL1
6    23DVL10
7   2016PP07

df$col <- as.integer(gsub('[a-zA-Z]', '', df$col))
df
      col
1 9667968
2 6796811
3    3666
4     610
5   23231
6    2310
7  201607
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63