Extract extension of file from working directory and check condition - r

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)

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

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
.....
}

Related

Setting default `.libPaths()` for multiple versions of R

I work in an environment with multiple versions of R available, managing my libraries can be something of a hassle as I have to switch library locations to avoid issues with packages being built under different versions of R.
Is there a way to change my default library location in .libPaths() automatically depending on the version of R i'm using?
I found this trick useful.
keep your locally installed R libraries in a directory named for their version, detect the version when R starts and set .libPaths() accordingly
Edit your .Rprofile file in you home directory to contain something like the following:
version <- paste0(R.Version()$major,".",R.Version()$minor)
if (version == "3.5.2") {
.libPaths( c("/path/to/Rlibs/3.5.2", .libPaths()) )
} else if (version == "3.4.3") {
.libPaths( c("/path/to/Rlibs/3.4.3", .libPaths()) )
}
Updated version that automatically creates a new library folder for a new R version if one is detected, also throws a warning when it does this in case you accidentally loaded a new R version when you weren't intending to.
# Set Version specific local libraries
## get current R version (in semantic format)
version <- paste0(R.Version()$major,".",R.Version()$minor)
## get username
uname <- Sys.getenv("USER") # USERNAME on windows because why make it easy?
## generate R library path for parent directory
libPath <- paste0("/home/", uname, "/Rlibs/")
setLibs <- function(libPath, ver) {
libfull <- paste0(libPath, ver) # combine parent and version for full path
if(!dir.exists(libfull)) { # create a new directory for this R version if it does not exist
# Warn user (the necessity of creating a new library may indicate an in advertant choice of the wrong R version)
warning(paste0("Library for R version '", ver, "' Does not exist it will be created at: ", libfull ))
dir.create(libfull)
}
.libPaths(c(libfull, .libPaths()))
}
setLibs(libPath, version)
A slightly shorter version of Richard J. Acton's solution:
version <- paste0(R.Version()$major,".",R.Version()$minor)
libPath <- path.expand(file.path("~/.R/libs", version))
if(!dir.exists(libPath)) {
warning(paste0("Library for R version '", version, "' will be created at: ", libPath ))
dir.create(libPath, recursive = TRUE)
}
.libPaths(c(libPath, .libPaths()))
I have a standard path structure with a new folder added for each version number, and a folder called pax for packages. To do this you just need to add the following to your .Rprofile.
Rver <- paste0(R.Version()$major, ".", R.Version()$minor)
.libPaths(file.path(paste0(
"C:/Users/abcd/R/", Rver, "/pax")))
This means you aren't going to grow a forest of if statements if you have multiple versions.

Can I get the URL of what will be used by install.packages?

When running install.packages("any_package") on windows I get the message :
trying URL
'somepath.zip'
I would like to get this path without downloading, is it possible ?
In other terms I'd like to get the CRAN link to the windows binary of the latest release (the best would actually be to be able to call a new function with the same parameters as install.packages and get the proper url(s) as an output).
I would need a way that works from the R console (no manual checking of the CRAN page etc).
I am not sure if this is what you are looking for. This build the URL from the repository information and building the file name of the list of available packages.
#get repository name
repos<- getOption("repos")
#Get url for the binary package
#contrib.url(repos, "both")
contriburl<-contrib.url(repos, "binary")
#"https://mirrors.nics.utk.edu/cran/bin/windows/contrib/3.5"
#make data.frame of avaialbe packages
df<-as.data.frame(available.packages())
#find package of interest
pkg <- "tidyr" #example
#ofinterest<-grep(pkg, df$Package)
ofinterest<-match(pkg, df$Package) #returns a single value
#assemble name, assumes it is always a zip file
name<-paste0(df[ofinterest,]$Package, "_", df[ofinterest,]$Version, ".zip")
#make final URL
finalurl<-paste0(contriburl, "/", name)
Here's a couple functions which respectively :
get the latest R version from RStudio's website
get the url of the last released windows binary
The first is a variation of code I found in the installr package. It seems there's no clean way of getting the last version, so we have to scrape a webpage.
The second is really just #Dave2e's code optimized and refactored into a function (with a fix for outdated R versions), so please direct upvotes to his answer.
get_package_url <- function(pkg){
version <- try(
available.packages()[pkg,"Version"],
silent = TRUE)
if(inherits(version,"try-error"))
stop("Package '",pkg,"' is not available")
contriburl <- contrib.url(getOption("repos"), "binary")
url <- file.path(
dirname(contriburl),
get_last_R_version(2),
paste0(pkg,"_",version,".zip"))
url
}
get_last_R_version <- function(n=3){
page <- readLines(
"https://cran.rstudio.com/bin/windows/base/",
warn = FALSE)
line <- grep("R-[0-9.]+.+-win\\.exe", page,value=TRUE)
long <- gsub("^.*?R-([0-9.]+.+)-win\\.exe.*$","\\1",line)
paste(strsplit(long,"\\.")[[1]][1:n], collapse=".")
}
get_package_url("data.table")
# on my system with R 3.3.1
# [1] "https://lib.ugent.be/CRAN/bin/windows/contrib/3.5/data.table_1.11.4.zip"

RUnit: could not find function "checkEquals"

I am creating an R package with the standard directory hierarchy. Inside the R directory, I create a test subdirectory.
In the R directory, I create a uTest.R file containing:
uTest <- function() {
test.suite <- defineTestSuite('test',
dirs = file.path('R/test'))
test.result <- runTestSuite(test.suite)
printTextProtocol(test.result)
}
In the R/test directory, I create a runit.test.R file containing:
test.validDim <- function() {
testFile <- "test/mat.csv"
generateDummyData(testFile,
10,
10)
checkEquals(validDim(testFile), TRUE)
}
I build and install my package using R CMD INSTALL --no-multiarch --with-keep.source RMixtComp in Rstudio. When I try to launch the function uTest(), I get this error message:
1 Test Suite :
test - 1 test function, 1 error, 0 failures
ERROR in test.validDim: Error in func() : could not find function "checkEquals"
However, if I call library(RUnit) prior to calling uTest(), everything works fine. In the import field of the DESCRIPTION file, I added RUnit, and in the NAMESPACE file I added import(RUnit).
How can I call uTest() directly after loading my package, without manually loading RUnit ?
You should not add RUnit to the Depends (or Imports) field in the DESCRIPTION file (despite the comment to the contrary). Doing so implies that the RUnit package is necessary in order to use your package, which is likely not the case. In other words, putting RUnit in Depends or Imports implies RUnit needs to be installed (Imports) and on the users' search path (Depends) in order for them to use your package.
You should add RUnit to the Suggests field in the DESCRIPTION file, then modify your uTest function as below:
uTest <- function() {
stopifnot(requireNamespace("RUnit"))
test.suite <- RUnit::defineTestSuite('test', dirs = file.path('R/test'))
test.result <- RUnit::runTestSuite(test.suite)
RUnit::printTextProtocol(test.result)
}
Doing this allows you to use RUnit for your tests, but does not require users to have RUnit installed (and possibly on their search path) in order to use your package. Obviously, they'll need RUnit if they wish to run your tests.

issue with get_rollit_source

I tried to use get_rollit_source from the RcppRoll package as follows:
library(RcppRoll)
get_rollit_source(roll_max,edit=TRUE,RStudio=TRUE)
I get an error:
Error in get("outFile", envir = environment(fun)) :
object 'outFile' not found
I tried
outFile="C:/myDir/Test.cpp"
get_rollit_source(roll_max,edit=TRUE,RStudio=FALSE,outFile=outFile)
I get an error:
Error in get_rollit_source(roll_max, edit = TRUE, RStudio = FALSE, outFile = outFile) :
File does not exist!
How can fix this issue?
I noticed that the RcppRoll folder in the R library doesn't contain any src directory. Should I download it?
get_rollit_source only works for 'custom' functions. For things baked into the package, you could just download + read the source code (you can download the source tarball here, or go to the GitHub repo).
Anyway, something like the following should work:
rolling_sqsum <- rollit(final_trans = "x * x")
get_rollit_source(rolling_sqsum)
(I wrote this package quite a while back when I was still learning R / Rcpp so there are definitely some rough edges...)

Using inst/extdata with vignette during package checking R 2.14.0

I have a package which contains a csv file which I put in inst/extdata per R-exts. This file is needed for the vignette. If I Sweave the vignette directly, all works well. When I run R --vanilla CMD check however, the check process can't find the file. I know it has been moved into an .Rcheck directory during checking and this is probably part of the problem. But I don't know how to set it up so both direct Sweave and vignette building/checking works.
The vignette contains a line like this:
EC1 <- dot2HPD(file = "../inst/extdata/E_coli/ecoli.dot",
node.inst = "../inst/extdata/E_coli/NodeInst.csv",
and the function dot2HPD accesses the file via:
ni <- read.csv(node.inst)
Here's the error message:
> tab <- read.csv("../inst/extdata/E_coli/NodeInst.csv")
Warning in file(file, "rt") :
cannot open file '../inst/extdata/E_coli/NodeInst.csv': No such file or directory
When sourcing ‘HiveR.R’:
Error: cannot open the connection
Execution halted
By the way, this is related to this question but that info seems outdated and doesn't quite cover this territory.
I'm on a Mac.
Have you tried using system.file instead of hardcoded relative paths?
EC1 <- dot2HPD(file = system.file("inst", "extdata", "E_coli", "ecoli.dot", package = "your_package+name"))
node.inst <- system.file("inst", "extdata", "E_coli", "NodeInst.csv", package = "your_package_name")

Resources