Rewrite a function in locked env - r

Using pvclust::pvclust , I got an error
Error in solve.default(crossprod(X, X/vv)) : Lapack routine dgesv:
system is exactly singular: U[2,2] = 0 Calls: ...
pvclust.merge -> lapply -> FUN -> msfit -> solve -> solve.default
Execution halted
I don't want stop analysis even if crossprod(X, X/vv) be singular matrix, so I tried to insert an if {...} block in pvclust::msfit to check whether crossprod(X, X/vv) is singular or not by matrixcalc::is.singular.matrix, and if it is so, return NA and continue.
After saved my.msfit.R which contain msfit which incerted if(!is.singular.matrix(...)) {...}else{...} in original pvclust::msfit,
methods::insertSource('/myFuncDir/my.msfit.R',package="pvclust",functions='msfit')
But I got error below
Error in assign(this, thisObj, envir = envwhere) :
cannot change value of locked binding for 'msfit'
In addition: Warning message:
In methods::insertSource(filename, package = "pvclust", functions = "msfit", :
cannot insert these (not found in source): "msfit"
Is there any solution? Should I request of the author of the pvclust package?
== Below added after posting ==
An accurate advice was given in comments to use try/catch syntax, but I don't think it will give me solution.
Concerning my poor English skill, I present a toy sample which tells the situation.
fun.a <- function(a1,a2,a3,a4){
sum1 <- a1 + a2
sum2 <- a2 + a3
sum3 <- a3 + a4
return(list(sum1,sum2,sum3))
}
fun.a(1,2,3,'Char')
Because that the sum3 will be an error, so fun.a(1,2,3,'Char') returns error.
But, I want to return
List [sum1, sum2, NaN]
If I use tryCatch(...,error=expr), sum1 to sum3(actually, solve(...)in pvclust::msfit) should be wrapped.
But, fun.a(msfit) is inner function of locked package(pvclust).

Related

could not find function "symbolicInt"

I simply cannot get these functions: symbolicInt and integral. Not sure why. I just re-installed everthing. I thought maybe it was becuase of the libraries but I tried each library, by itself; did not work.
For example, according to documentation of
Document of symbolicInt
Document of integral
Current R Versions:
R 4.2
R42-tools are downloaded.
Code:
library('mosaic')
library('mosaicCore')
library('mosaicCalc')
f <- function(x){a * x^2 ~ x}
F = antiD(a * x^2 ~ x, a = 1)
F
symbolicInt(f )
f = integral( 3*x**2 ~ x)
f(from=1,to=4)
Result:
Error in symbolicInt(f) : could not find function "symbolicInt"
Error in integral(f ~ x) : could not find function "integral"
Edit: I am able to use symbolicInt by mosaicCalc:::symbolicInt ; but I cannot process this function:
(x/sigma**2)*exp((-x**2)/2*sigma**2 )
It gives following error:
Error in .intArith(form, ...) :
Error: symbolic algorithm gave up
6. stop("Error: symbolic algorithm gave up")
5. .intArith(form, ...)
4. symbolicAntiD(lform, ...)
3. .intArith(form, ...)
2. symbolicAntiD(form, ...)
1. sI((x/sigma^2) * exp((-x^2)/2 * sigma^2) + 1 ~ x)

Unexpected symbol error in R that doesn't match my code

I am coding in R-studio and have a function called saveResults(). It takes:
sce - a Single Cell Experiment object.
opt - a list with five things
clusterLabels - simple dataframe with two columns
The important thing is that I receive an error stating:
Error: unexpected symbol in:
"saveResults(sce = sce, opt = opt, clusteInputs()
zhengMix"
which doesn't agree at all with the parameters I pass into the function. You can see this on the last line of the code block below: I pass in proper parameters, but I receive an error that says I have passed in clusteInputs(), and zhengMix instead of clusterLabels. I don't have a function called clusteInputs(), and zhengMix was several lines above.
# Save the clustering data
InstallAndLoadPackagesForSC3Clustering()
opt <- GetOptionInputs()
zhengMix <- FetchzhengMix(opt)
sce <- CreateSingleCellExperiment(zhengMix)
clusterLabels <- getClusterLabels(sce)
opt <- createNewDirectoriesToSaveData(opt)
saveResults <- function(sce, opt, clusterLabels){
print("Beginning process of saving results...")
maxClusters = ncol(clusterLabels)/2+1
for (n in 2:maxClusters){
savePCAasPDF(sce, opt, numOfClusters = n, clusterLabels)
saveClusterLabelsAsRDS(clusterLabels, numOfClusters = n, opt)
}
saveSilhouetteScores(sce, opt)
print("Done.")
}
saveResults(sce = sce, opt = opt, clusterLabels = clusterLabels)
Does anyone have an idea what is going on? I'm pretty stuck on this.
This isn't the best solution, but I fixed my own problem by removing the code out of the function and running it there caused no issues.

compute an integration

Here is my integrand()
integrand<-function(x,vecC)
{
as.numeric((2/(b-a))*vecC%*%as.matrix(cos((x-hat.a)
*(seq(0,N-1,length=N)*pi/(b-a)))))
}
it can produce the value. For example, for
a<-1
b<-10
vecC<-t(as.matrix(rnorm(80)))
hat.a<--1.2
N<-80
I get
> integrand(1.4,vecC)
[1] -0.3635195
but I met problem when I run the following code for integration
> integrate(function(x){integrand(x,vecC)},upper = 3.4,lower = 1)$value
and the error message is
Error in integrate(function(x) { :
evaluation of function gave a result of wrong length
In addition: Warning message:
In (x - hat.a) * (seq(0, N - 1, length = N) * pi/(b - a)) :
longer object length is not a multiple of shorter object length
If you read the help page for integrate you will see that the function passed to integrate should return a vector.
So the solution to your error is to use Vectorize like this
Define your function separately as
f <- function(x){integrand(x,vecC)}
Now define a vectorized version of this function like so
fv <- Vectorize(f,"x")
and then
integrate(fv,upper = 3.4,lower = 1)$value
will give you a result.

Reducing equations using R

I've got this small snippet for reducing a large system:
# set up the multipliers
g1 = (s+9)/((s)*(s+6)*(s+12)*(s+14))
g2 = ((6)*(s+9)*(s+17))/((s+12)*(s+32)*(s+68))
h1 = 13
h2 = 1/(s+7)
# reduce the system in parts
s1 = (g2)/(1 + (g2)*(h1))
s2 = (s1)*(g1)
s3 = (s2)/(1 + (s2)*(h2))
# now we have a unity feedback
g = s3
show(g)
g should be the reduced equation from doing the operations above. However, I get a bunch of errors when I run the code:
Error : object 's' not found
Error : object 's' not found
Error : object 's' not found
Error : object 'g2' not found
Error : object 's1' not found
Error : object 's2' not found
Error : object 's3' not found
Error : error in evaluating the argument 'object' in selecting a method for function 'show': Error: object 'g' not found
Am I not using equations correctly?
edit: my intentions are to have s as a free variable
In order to evaluate your first line of code, there must be an object s that is already defined.
It sounds like your goal is to create a function that outputs g from a single input s. The below code wraps your calculations in a function called make_g:
make_g <- function(s){
# set up the multipliers
g1 = (s+9)/((s)*(s+6)*(s+12)*(s+14))
g2 = ((6)*(s+9)*(s+17))/((s+12)*(s+32)*(s+68))
h1 = 13
h2 = 1/(s+7)
# reduce the system in parts
s1 = (g2)/(1 + (g2)*(h1))
s2 = (s1)*(g1)
s3 = (s2)/(1 + (s2)*(h2))
# now we have a unity feedback
g = s3
g
}
Now, you can call the functions using whatever value for s you like:
make_g(s = 1)

Logging and writing error messages to a dataframe

I intend to record the errors in my R code while calling functions in a dataframe (ERR_LOG, say). I want to use 'try' to identify errors while calling a function,if any.The dataframe(ERR_LOG) will have the following columns :
Time : The time at which the function was called (Sys.time)
Loc : For which function call was this error recorded (name of the
function)
Desc : Description of the error which R throws at us (Error message
in R)
Example :
First I would like to initialize a blank dataframe 'ERR_LOG' with these columns
Then write the function
f <- function(a){
x <- a*100
return(x)
}
Now I put the output of the call to 'f' in 'chk'
chk <- try(f())
The above call gives the error 'Error in a * 100 : 'a' is missing' (description of the error)
Check
if(inherits(chk,'try-error'))
{then I want to populate ERR_LOG and stop the code execution}
How can this be done in R?
use tryCatch instead of try
Then inside tryCatch(), use the argument error=function(e){}
e will have an element named message, which is what you would like
Use the following call with browser to explore e$message:
x <- tryCatch(stop("This is your error message"), error=function(e) {browser()})
Note that your function need not be anonymous.
MyErrorParser <- function(e) {
m <- e$message
if (grepl("something", m))
do something
return (something_else)
}
## THEN
tryCatch(stop("This is a test"), error=MyErrorParser)

Resources