Edit: This question has been flagged as a duplicate of another question related to Rstudio. I would like to clarify that I am running this file with the command R -f figures.R
and have never used Rstudio before. While some answers such as https://stackoverflow.com/a/27201707/118153 appear to be relevant, it does not answer why the code operates fine without the if
. Answers to the linked question would appear to imply it should not work at all, while it does work without the if
.
I would like to selectively build figures for my paper, regenerating only those which I have deleted. However, the following code produces a .tex
file with only two comment lines; when run without the if
around it, it correctly produces the whole file. I am an R novice - this core code itself comes from a statistical consultant.
Why does the following code not produce the figure when inside an if
, but it produces the figure when not inside an if
?
figure <- '../paper/figures/recall_by_choices.tex'
if (!file.exists(figure)) {
tikz(file=figure,width=3.5, height=2)
mem1percent <- mem |>
group_by(choices, success1) |>
summarize(count=n()) |>
mutate(Percent = count/sum(count) * 100)
mem1percent |>
ggplot(aes(x=factor(choices), y=Percent, fill=success1)) +
geom_bar(stat='identity', position=position_dodge(), color='black') +
labs(x="Choices", fill="7-day Recall") +
scale_fill_manual(values=c('black','grey'))
dev.off()
}
A similar example appears to run fine within an if
, not using ggplot
:
figure <- '../paper/figures/hmn_density.tex'
if (!file.exists(figure)) {
tikz(file=figure,width=7, height=4)
hmn <- table(ifelse(surveys$how_many == 'own' | surveys$how_many == 'n/a' | surveys$how_many == 'lots' | surveys$how_many == '', NA, ifelse(surveys$how_many == 'inf' | nchar(surveys$how_many) > 5, 100000, as.numeric(surveys$how_many))))
plot(density(hmn), main='', xlab='Number of Choices')
dev.off()
}
Perhaps ggplot
is causing the problem? Both give output with warnings when the if
condition is true:
`summarise()` has grouped output by 'choices'. You can override using the `.groups` argument.
null device
1
null device
1
Warning message:
In ifelse(surveys$how_many == "inf" | nchar(surveys$how_many) > :
NAs introduced by coercion