1

Possible Duplicate: Extract file extension from file path

I am in a state where i need to check the extension of files in my working directory and take some decision. I check it by list.files() and it gives me all the files in the working directory with extension. I get a list like

"GSM18423_PA-D_132.cel"        "GSM18424_PA-D_206.cel"        "GSM18425_PA-D_216.cel" 

Now further I want a condition, if a file has extension .cel do something like below.

if(extension==".cel")
...... else
......

As i looked for tools package, but not working in my R version of R version 3.1.3 RC (2015-03-06 r67947) . I tried install.packages("tools") which pops up a window and asks to restart my system before installing but finally does nothing even no restart also. Finally i get a message

Installing package into ‘/home/hussain/R/i686-pc-linux-gnu-library/3.1’
(as ‘lib’ is unspecified)
Warning in install.packages :
  package ‘tools’ is not available (for R version 3.1.3 RC)
Community
  • 1
  • 1
Agaz Wani
  • 5,514
  • 8
  • 42
  • 62
  • possible duplicate of [Extract file extension from file path](http://stackoverflow.com/questions/7779037/extract-file-extension-from-file-path) – zx8754 Apr 14 '15 at 12:58
  • @zx8754 . Already mentioned above – Agaz Wani Apr 14 '15 at 12:59
  • Mentioning it as a duplicate, doesn't make it any less duplicate. This post is a more suitable as a comment to original post. – zx8754 Apr 14 '15 at 13:02
  • @zx8754 You are right. Should not it be asked if not solved from the original post . – Agaz Wani Apr 14 '15 at 13:05
  • 2
    I dont think you need to install `tools`, just load it with `library`. Is this enough to check the extensions: `grepl("*.cel", lst)` (where `lst` is the result from your `list.files` – user20650 Apr 14 '15 at 13:08

2 Answers2

4

This is the source-code of tools::file_ext

function (x) 
{
    pos <- regexpr("\\.([[:alnum:]]+)$", x)
    ifelse(pos > -1L, substring(x, pos + 1L), "")
}

just create your own function with this code

Rentrop
  • 20,979
  • 10
  • 72
  • 100
2

With reference to the comment @user20650, i think it would be easy to do something like

lst <- list.files()
ext <- grepl("*.cel$", lst)[1]
if(ext)
{ .....
code
....
}else{
....
code
.....
}
zx8754
  • 52,746
  • 12
  • 114
  • 209
Agaz Wani
  • 5,514
  • 8
  • 42
  • 62