R : How to suppress a persistent warning message from alpha() function in my Rmd output? - r

Program : R 3.2.1 for Mac OSX
IDE : RStudio
Output : rmkd > html
Package : "psych"
Function : alpha()
Problem :
While using alpha(data, na.rm=F, check.keys=F, delete=F), because portions of the input-data is negatively correlated and because I have check.keys = FALSE, I get the following message :
Some items XXX were negatively correlated with the total scale and
probably should be reversed. To do this, run the function again with
the 'check.keys=TRUE' option
Question :
My check.keys is set intentionally. Fully understanding the implications of the warning & mostly for aesthetic and educational reasons, how can I suppress it in my output?
Attempts so far :
1. I've tried suppressWarnings() & suppressMessages().
2. I've tried invisible() & sink(., type="message").
3. In the Rmd block, I've tried : ```{r warning=F, message=F}
4. Exploring print(alpha) I found what I think is the origin. Maybe someone understands how to suppress this part of the code? :
`p1 <- principal(x)
if (any(p1$loadings < 0)) {
if (check.keys) {
warning("Some items were negatively correlated with total scale and were automatically reversed.\n This is indicated by a negative sign for the variable name.")
keys <- 1 - 2 * (p1$loadings < 0)
}
else {
warning("Some items were negatively correlated with the total scale and probably should be reversed. To do this, run the function again with the 'check.keys=TRUE' option")
cat("Some items (", rownames(p1$loadings)[(p1$loadings < 0)], ") were negatively correlated with the total scale and probably should be reversed. To do this, run the function again with the 'check.keys=TRUE' option")
}
}`
thanks!

The culprit here is cat, which will not heed suppressMessages etc.
To catch it, you can use capture.output instead:
invisible(capture.output(alpha(data, na.rm=F, check.keys=F, delete=F)))
capture.output calls sink(…, type = "output") internally and discards/returns the result.

Related

Error in if (more || nchar(output) > 80) when using mgcv

I have the same problem with this one but no solutions found yet
.
Error in if (more || nchar(output) > 80) { : missing value where TRUE/FALSE needed
I am conducting analysis using the mgcv package.
model1<-gam(fm_xsetz~total_pm2.5, data=analysis)
I can get the results by using the summary(). But when I try to open the model in the global environment, I get the warning:
Error in if (more || nchar(output) > 80) { : missing value where
TRUE/FALSE needed
Is anyone has the same problem?
FYI,when you use the following code:
library(geostatsp)
data(swissRain)
same problem happens!
I have/had a similar problem when I tried to view a List generated trough a function that computes the intersect/difference of two sets of 23000 observations each.
The function in question:
jeepers.creepers<-function(dfx,dfy,by.x,by.y){
SetX<-dfx[[by.x]]
SetY<-dfy[[by.y]]
Union.X.Y<-intersect(SetX,SetY)
Difference.in.X<-setdiff(SetX,Union.X.Y)
Difference.in.Y<-setdiff(SetY,Union.X.Y)
result<-list(Union.X.Y,Difference.in.X,Difference.in.Y)
names(result)<-c("Union of SetX and SetY",
"Unique in SetX",
"Unique in SetY")
return(result)
}
It gave me this error:
Error in if (more || nchar(output) > 80) { :
missing value where TRUE/FALSE needed
Nevertheless I could view the elements individually with
View(list$element)
I had a similar problem yet I could view it with:
view(as.data.frame(df))

Select any character string over an NA in an If statement in R

I am trying to create a function which will look at two vectors of character labels, and print the appropriate label based on an If statement. I am running into an issue when one of the vectors is populated by NA.
I'll truncate my function:
eventTypepriority=function(a,b) {
if(is.na(a)) {print(b)}
if(is.na(b)) {print(a)}
if(a=="BW"& b=="BW",) {print("BW")}
if(a=="?BW"& b=="BW") {print("?BW")}
...#and so on
}
Some data:
a=c("Pm", "BW", "?BW")
b=c("PmDP","?BW",NA)
c=mapply(eventTypepriority, a,b, USE.NAMES = TRUE)
The function works fine for the first two, selecting the label I've designated in my if statements. However, when it gets to the third pair I receive this error:
Error in if (a == "?BW" & b == "BW") { :
missing value where TRUE/FALSE needed
I'm guessing this is because at that place, b=NA, and this is the first if statement, outside of the 'is.na' statements, that need it to ignore missing values.
Is there a way to handle this? I'd really rather not add conditional statements for every label and NA. I've also tried:
-is.null (same error message)
-Regular Expressions:
if(a==grepl([:print:]) & b==NA) {print(a)}
In various formats, including if(a==grepl(:print:)... No avail. I receive an 'Error: unexpected '[' or whatever character R didn't like first to tell me this is wrong.
All comments and thoughts would be appreciated. ^_^
if all your if conditions are exclusives, just call return() to avoid checking other conditions when one is met:
eventTypepriority=function(a,b) {
if(is.na(a)) {print(b);return()}
if(is.na(b)) {print(a);return()}
if(a=="BW"& b=="BW",) {print("BW");return()}
if(a=="?BW"& b=="BW") {print("?BW");return()}
...#and so on
}
You need to use if .. else statements instead of simply if; otherwise, your function will evaluate the 3rd and 4th lines even when one of the values is n/a.
Given you mapply statement, I also assume you want the function to output the corresponding label, not just print it?
In that case
eventTypepriority<-function(a,b) {
if(is.na(a)) b
else if(is.na(b)) a
else if(a=="BW"& b=="BW") "BW"
else if(a=="?BW"& b=="BW") "?BW"
else "..."
}
a=c("Pm", "BW", "?BW")
b=c("PmDP","?BW",NA)
c=mapply(eventTypepriority, a,b, USE.NAMES = T)
c
returns
Pm BW ?BW
"..." "..." "?BW"
If you actually want to just print the label and have your function return something else, you should be able to figure it out from here.

HMM Error in if (d < delta) { : missing value where TRUE/FALSE needed

I have some problems with the viterbiTraining function from the HMM package.
I tried using it on a pretty straightforward hmm and a vector of observations.
Here's the code:
Emisije<-rep("IntervalC",length(Cl1.res))
Emisije[IntervalA[,1]]<-"IntervalA"
Emisije[IntervalB[,1]]<-"IntervalB"
The Emisije vector looks like this:
head(Emisije)
[1] "IntervalA" "IntervalA" "IntervalA" "IntervalC" "IntervalB" "IntervalA"
startProbs<-c(0.6873065,0.3126935)
transProbs<-matrix(c(0.8, 0.7, 0.2,0.3),ncol=2)
emissionProbs<-matrix(rep(1/3,6),ncol=3)
stanji<-initHMM(c("NizkaVar", "VisokaVar"), c("IntervalA", "IntervalB",
"IntervalC"), startProbs, transProbs, emissionProbs)
After running this everything works, except for the viterbiTraining function, which gives the following result:
viterbiTraining(stanji,Emisije)
Error in if (d < delta) { : missing value where TRUE/FALSE needed
Even the similar function baumWelch, which takes the exact same parameters, works without errors, so I really don't understand what's wrong here.
Can anyone please explain to me what I am doing wrong? Thank you in advance.

removeSource() with `[` subset fails on empty j argument

This is a follow-up to removeSource() returning error on internal package function.
In that question, it was pointed out that there may be a bug in removeSource() when the function uses [ subsetting. I want to focus on that issue, so I wrote a new question here.
When the j argument in [ is empty, removeSource() fails.
Here's an example.
foo <- function(x) { x[1, ] }
removeSource(foo)
# Error in recurse(part[[i]]) : argument "part" is missing, with no default
bar <- function(x) { x[1, seq_along(x)] }
removeSource(bar)
# function (x)
# {
# x[1, seq_along(x)]
# }
I'm hesitant to call it a bug, so I'll first ask if this was done intentionally? Also, suppose I submitted the foo() function in a package to CRAN. Would it pass the testing?
Updates:
Sept 1, 2014: Bug report filed https://bugs.r-project.org/bugzilla/show_bug.cgi?id=15957
Sept 21, 2014: This was indeed a bug and according to the confirmed bug report is "soon to be fixed in R-devel and R-patched."
Fixed in version R 3.1.2
I'd say it was a bug. No sign of it reported here though:
https://bugs.r-project.org/bugzilla3/buglist.cgi?quicksearch=removeSource
Interestingly you get a different error once you try and debug the function by making a local copy.
> dput(removeSource,file="rs.tmp.R")
> rs = dget("rs.tmp.R")
rs is now a copy of removeSource, but not in the environment of the utils package.
> foo = function(x){x[1,]}
> rs(foo)
Error in `attr<-`(`*tmp*`, "srcref", value = NULL) : '*tmp*' is missing
> removeSource(foo)
Error in recurse(part[[i]]) : argument "part" is missing, with no default
rs works fine on a function without missing subs:
> bar = function(x){x[1]}
> rs(bar)
function (x)
{
x[1]
}
If you want a really minimal failing example, you don't need any subscripts or commas:
> foo = function(x){x[]}
> removeSource(foo)
Error in recurse(part[[i]]) : argument "part" is missing, with no default
I doubt this will trigger any CRAN flags since missing dimensions in subscripts probably occur in 90% of the packages currently on there...
Suggest you report it on the bug tracker, or ask on R-devel mailing list.

R numeric variable, non null, non na but empty

Hi eveyrone ##.
I got some problem with R that I can't fix: Currently i'm working with GEOquery package and I want to retrieve some informations in metadata of gse files.
More precisely I'm looking for the channel label (for exemple Cye3). Here's a sample of my code :
>library(GEOquery)
>gse<-getGEO("GSE2253",GSEMatrix=TRUE,destdir=".")
>gse<-gse[[1]]
>gse$label_ch1[1]
V2
Levels: According to Affymetrix protocol (biotin)`
And here's my problem
`> is.na(gse$label_ch1[1])
V2
FALSE
> is.null(gse$label_ch1[1])
[1] FALSE`
This GSE file is a text file and in the line corresponding to the label (!Sample_label_ch1) there is no value.So, here's what I'v done for my work:
`if(is.na(gse$label_ch1[1])){
color<-"Non specified"
} else {
label<-gse$label_ch1[1]
}`
So, if I got no informations for the channel I just say "non specified", else, I return the value. But I'v got error with this if/else statement in my script:
Error in if (file == "") file <- stdout() else if (is.character(file)) { :
the length of argument is null
Sorry if the error traduction is not exact, my R version is in French ^^.
I tried
if(as.character(gse$label_ch1[1])=="")
But it doesn't work either
If someone has an idea to help me ^^
Thanks in advance!
Script:
sample<-NULL
output<-NULL
gse<-NULL
color<-NULL
series_matrix<-dir(getwd(),pattern="*series_matrix.txt")
series_matrix<-unlist(strsplit(series_matrix,"_")[1])
for(i in 1:length(series_matrix)){
gse<-getGEO(series_matrix[i],GSEMatrix=TRUE,destdir=".")
gse<-gse[[1]]
if(length(gse$label_ch1[1])==0){
color<-"Non specified"
} else {
color<-gse$label_ch1[1]
}
print (color)
sample<-cbind(as.character(gse$title),as.character(gse$geo_accession))
outputsample<-paste(getwd(),"/sample.txt",sep="")
write.table(paste("txt",color,sep=""),output,
row.names=FALSE,col.names=FALSE,sep="\t",quote=FALSE)
write.table(sample,outputsample,
row.names=FALSE,col.names=FALSE,sep="\t",quote=FALSE,append=TRUE)
Feature_Num<-list(1:length(featureNames(gse)))
Gene_Symbol<-pData(featureData(gse)[,11])
Probe_Name<-pData(featureData(gse)[,1])
Control_Type<-pData(featureData(gse)[,3])
liste<-as.character(sampleNames(gse))
for(i in 1:lenght(liste)){
values<-cbind(Feature_Num,Gene_Symbol,Probe_name,Control_Type,exprs(gse)[,i])
colnames(values)<-c("Feature_Num","Gene_Symbol",
"Probe_Name","Control_Type","gMedianSignal")
write.table(values,paste(getwd(),"/Ech",liste[i],".txt",sep=""),
row.names=FALSE,quote=FALSE,sep="\t")
}
}
Don't hesitate if you want explication about lines in this script
Yes, in R you can create a zero-length object:
foo<-vector()
foo
logical(0)
Then change it:
foo<-NULL
foo
NULL
It's confusing at first, but if you ever took some abstract algebra, you may remember the difference between the "empty set" and a set whose only element is the "empty set."
Asking on other forum I finally get a solution for this non NULL/non NA problem:
the gse$label_ch1[1] is numeric of length 1
> length(gse$label_ch1[1])
[1] 1
but we can transform this variable in character:
> as.character(gse$label_ch1[1])
[1] ""
and with this line
> nchar(as.character(gse$label_ch1[1]))
[1] 0
we can see that I can see if the gse$label_ch1[1] value is really empty or not
Thank you all for your help!
Cheers

Resources