Confused by stat function - julia

I'm trying to detect whether or not a given path is a file or a directory:
map(stat, readdir("./"))
#=
StatStruct(mode=040775, size=4096)
StatStruct(mode=040775, size=4096)
=#
This is correct, I have two directories in my cwd. However, when I try to stat the directory:
map(stat, readdir("./mydir"))
I get
#=
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
StatStruct(mode=000000, size=0)
=#
Which makes no sense to me at all. I have both files and folders in mydir. What is happening?

Look at what the output of readdir("./mydir") is — it's just the filenames inside that folder, without mydir/ prepended. You're invoking stat from your current working directory with the filenames from a different directory.
In order for this to work, you need to either move to mydir or manually prepend mydir/ to your filenames:
cd("./mydir") do
map(stat, readdir())
end
or
map(f -> stat(joinpath("mydir", f)), readdir("./mydir"))

Related

Issue when knitting with rmarkdown and latex distribution

[WARNING] Deprecated: --self-contained. use --embed-resources --standalone
! Missing $ inserted.
<inserted text>
$
l.100 ![](methods_
files/figure-latex/plot-1.pdf)<!-- -->
Try to find the following text in methods.Rmd:
![](methods_
You may need to add $ $ around a certain inline R expression `r ` in methods.Rmd (see the above hint). See https://github.com/rstudio/rmarkdown/issues/385 for more info.
Error: LaTeX failed to compile methods.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See methods.log for more info.
Execution halted
I get this error message when I try to knit my methods section document. Everything seems to work fine if I delete the following code chunk:
#Overlaying both groups to see which questions show most differences in performance between them
ggplot(mapping = aes(x, y)) +
geom_bar(data = nonrankedplayers, aes(x= questions , y=scoreNR), width = 0.8, stat = 'identity', fill= 'darkgrey') +
geom_bar(data = rankedplayers, aes(x= questions , y=scoreR), width = 0.4, stat = 'identity') +
theme_classic() +
ggtitle("Percentage of participants knowing the answer per group")+
theme(plot.title = element_text(hjust = 0.5))+ #centre the title
scale_x_discrete("Question", breaks = seq(0,26, by = 1) )+
scale_y_continuous("Percentage correct", breaks = seq(0,1, by = 0.1))
I tried adding $ between the code chunk, but then R does not recognise it.

Non-numeric argument error to binary operation in R, needs explanation

This is a continuation of (how to modify axis labels ggplot in R). The code supplied works beautifully. The data is created manually. So I transferred that a larger dataset and am now getting the following error.
Error in aes(y = AnnualDifference, x = (reorder(Seriesttls, AnnualDifference))) + :
non-numeric argument to binary operator
This is the code being used
jobgrowthbyindustry<-ggplot(data=nvces2, aes(y=AnnualDifference,x=
(reorder(Seriesttls,AnnualDifference)))+geom_col(color="blue")
+coord_flip()+labs(x=NULL)+ggtitle("Nevada Nonfarm Job Growth by Industry"))+
theme(plot.title.position = "plot",
plot.title = element_text(hjust =0.5))
If this is of any assistance, the AnnualDifference item is created using the following code
nvces<- nvces%>%
group_by(adjusted,areaname,seriescode)%>%
mutate(PreviousYear=lag(ravg,12),
PreviousMonth=lag(ravg),
AnnualDifference=ravg-PreviousYear,
MonthlyDifference=ravg-PreviousMonth,
MonthlyGrowthRate=MonthlyDifference/PreviousMonth,
PercentGrowthRate=AnnualDifference/PreviousYear)%>%
ungroup()
Where my confusion comes is that the data types for the items involved in the chart are the same. Seriesttls is character and AnnualDifference (or A in the previous question) is numeric. Yet in the first I get no errors and in the second one, I do. Any thoughts on why this is?
In my experience, this error typically pops up if I got one of the parentheses wrong and am trying to add something within the call to ggplot. Your formatting makes this difficult to see, so let's look at this more nicely formatted:
jobgrowthbyindustry <-
ggplot(data=nvces2,
aes(y = AnnualDifference,
x = (reorder(Seriesttls,AnnualDifference))
)
+ geom_col(color="blue")
+ coord_flip()
+ labs(x=NULL)
+ ggtitle("Nevada Nonfarm Job Growth by Industry")
) + theme(plot.title.position = "plot",
plot.title = element_text(hjust =0.5)
)
One of the parentheses is misplaced.
It should be:
jobgrowthbyindustry <-
ggplot(data=nvces2,
aes(y = AnnualDifference,
x = (reorder(Seriesttls,AnnualDifference))
)
) +
geom_col(color="blue") +
coord_flip() +
labs(x=NULL) +
ggtitle("Nevada Nonfarm Job Growth by Industry") +
theme(plot.title.position = "plot",
plot.title = element_text(hjust =0.5)
)
And you can also remove the redundant () around the call to reorder.
If this is not resolving your issue, please do provide some data so that we can reproduce the error.

Wait for completion of previous code chunk in R. Make sure it completes before proceeding

Is there a way for R to wait for the completion of the first chunk before proceed to the second? Or make sure it completes before going to the next line?
Almost complete reproducible code is here: ggplot piecharts on a ggmap: labels destroy the small plots
The code generates small ggplots on a ggmap. It works great if executed chunk by chunk. But if I run the whole code it fails to generate the plot.
When I restart the first section of the code I finally get the message of what happened earlier:
Warning message:
In unit %in% c("grobx", "groby", "grobwidth", "grobheight", "grobascent", :
reached elapsed time limit
I see that I cannot run chunks of the code below both at once, I need to run the first, see the cursor prompt indicate that I can go ahead with the next:
df.grobs <- df %>%
do(subplots = ggplot(., aes(1, sales, fill = component)) +
geom_bar(position = "stack", alpha = 0.5, colour = "white", stat="identity") +
geom_text( aes(label = round(sales), y=sales), position = position_stack(vjust = 0.5), size = 2.5) +
coord_polar(theta = "y") +
scale_fill_manual(values = c("green", "red"))+
theme_void()+ guides(fill = F)) %>%
mutate(subgrobs = list(annotation_custom(ggplotGrob(subplots),
x = lon-Potential_Sum/300, y = lat-Potential_Sum/300,
xmax = lon+Potential_Sum/300, ymax = lat+Potential_Sum/300)))
df.grobs %>%
{p +
.$subgrobs +
#geom_text(data=df, aes(label = round(Potential_Sum,0)), size=2.5) +
geom_col(data = df,
aes(0,0, fill = component),
colour = "white")+ geom_text(data=df, aes(label = Miasto),nudge_y = -0.15, size=2.5)}
I presume R does not wait for the completion of the first chunk and proceeds to the second. How to make sure it is done with the first and wait with the execution of the second chunk? I tried various solutions for making the script interactive or wait sys.sleep(1) but it did not work. I presume do command iterations may have something to do with it.
My best shot thus far:
Delay <- function(wait = 1000) {
n <- as.numeric(Sys.time()) + wait / 1000
while (as.numeric(Sys.time()) < n) {}
}
plot(graph)
### Time-out to finish preview of plot
Delay(some time in milliseconds)
### Plot to file if result is OK
sel_yesno <- tk_messageBox(type = "yesno", paste("Save plot to file?"))
around 1.5 seconds for an easy ggplot seems needed but very complex plots can take a whole lot of added time.

Embed ggplot2 Graph in Knitr Document: Unable to find function ggplot

I am working on a document and am using both knitr and ggplot2. I am new to knitr and TeX itself and therefore not overly familiar with all that I am doing.
When I open RStudio to do the work, I first run the following two commands:
require("knitr")
require("ggplot2")
I then click on the Compile PDF. I have the following code that throws an error:
<<histogram, echo=FALSE, fig.align='center'>>=
summary(los$hosp_svc)
summary(los$Pt_Age)
binsize = diff(range(los$Pt_Age)/30)
ggplot(los, aes(x = Pt_Age)) +
geom_histogram(binwidth = binsize, fill = "red",
alpha = 0.315, colour = 'black') +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
xlab("Patient Age in Years") +
ylab("Frequency/Count") +
ggtitle("Histogram of Patient Age")
#
The error that I am getting is that the ggplot function could not be found, which is odd because if I just run the above code in the console the graph produces just find, so I know the package is loaded and available for use.
Any thoughts?
Thank you,
When working with .Rnw files (or .Rmd files), be sure to include any library calls in your script (see below). When you press the "Compile PDF" button, the R code in your script is submitted to a new instance of R to prevent anything in your current environment from mucking up the results. This might seem a little strange, but is good for reproducibility. So objects that aren't created explicitly via your script and packages that aren't called explicitly in your script will be forgotten as soon as you hit "Compile PDF"
<<histogram, echo=FALSE, fig.align='center'>>=
library(ggplot2)
summary(los$hosp_svc)
summary(los$Pt_Age)
binsize = diff(range(los$Pt_Age)/30)
ggplot(los, aes(x = Pt_Age)) +
geom_histogram(binwidth = binsize,
fill = "red",
alpha = 0.315,
colour = 'black') +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
xlab("Patient Age in Years") +
ylab("Frequency/Count") +
ggtitle("Histogram of Patient Age")
#

Tcl/Tk Referencing user-selected values in script

A quick question regarding Tcl/Tk and R. Below I have a slice of code that corresponds with a Tk button that executes the ToDo<-function(){...}.
My presumption is that both summary.myData() and ggplot() commands will execute. With this said, my question is whether or not I have correctly coded each command to reference the correct selected variable (the tk widget controlling this is working just fine, thus not depicted).
Namely if the arguments for each command are valid.
summary.myData<-summarySE(myData, measurevar=paste(tx.choice1), groupvars=paste(tx.choice2),conf.interval=0.95,na.rm=TRUE,.drop=FALSE)
would be read by R as
summary.myData<-summarySE(myData, measurevar=Measure, groupvars=Group,conf.interval=0.95,na.rm=TRUE,.drop=FALSE)
and
ggplot(data=summary.myData,aes(x=paste(tx.choice2),y=paste(tx.choice1)))+
geom_errorbar(aes(ymin=formula(paste(tx.choice1),"-ci"),ymax=formula(paste(tx.choice1),"+ci")), colour="black", width=.5, position=pd)+
geom_point(position=pd, size=3)+
labs(title=paste("Interval Plot of",tx.choice1,"By",tx.choice2))
will be read as
ggplot(data=summary.mydata, aes(x=Group, y=Measure))+
geom_errorbar(aes(ymin=Measure-ci, ymax=Measure+ci), colour="black", width=.5, position=pd)+
geom_point(position=pd, size=3)+
labs(title = "New plot title",x="X",y="y")
The slice for reference:
ToDo<-function(){
tx.choice1<<-vars.name.num[as.integer(tkcurselection(tl1))+1]
tx.choice2<<-vars.name.fac[as.integer(tkcurselection(tl2))+1]
numb.select.num<<-length(tx.choice1)
numb.select.fac<<-length(tx.choice2)
windows()
if (numb.select.num!=0){
if (numb.select.fac==0){
stop(tkmessageBox(message="Please select at least one categorical variable!", icon="error"))
}
else if (numb.select.fac==1) {
if(tclvalue(intervalplot_title)=="" & tclvalue(intervalplot_x)=="" & tclvalue(intervalplot_y)==""){
summary.myData<-summarySE(myData, measurevar=paste(tx.choice1), groupvars=paste(tx.choice2),conf.interval=0.95,na.rm=TRUE,.drop=FALSE)
ggplot(data=summary.myData,aes(x=paste(tx.choice2),y=paste(tx.choice1)))+
geom_errorbar(aes(ymin=formula(paste(tx.choice1),"-ci"),ymax=formula(paste(tx.choice1),"+ci")), colour="black", width=.5, position=pd)+
geom_point(position=pd, size=3)+
labs(title=paste("Interval Plot of",tx.choice1,"By",tx.choice2))
} else {
summary.myData<-summarySE(myData, measurevar=paste(tx.choice1), groupvars=c(paste(tx.choice2)),conf.interval=0.95,na.rm=TRUE,.drop=FALSE)
ggplot(data=summary.myData,aes(x=paste(tx.choice2),y=paste(tx.choice1)))+
geom_errorbar(aes(ymin=paste(tx.choice1)-ci,ymax=paste(tx.choice1)+ci), colour="black", width=.5, position=pd)+
geom_point(position=pd, size=3)+
labs(title=tclvalue(intervalplot_title),x=tclvalue(intervalplot_x),y=tclvalue(intervalplot_y))
}
tkinsert(txt,"end",paste("\nIntervalplot of", tx.choice1,"By",tx.choice2[1],"\n\n"))
}
}
Figured it out, the correct usage would just be paste(tx.choice1,"-ci"). There is no need to add the formula() condition.

Resources