I am running the following loop in a function:
for (i in 1:400) {
m<-update_values() # Updates values in the dataframe
dygraph(m[,1:4]) %>%
dyCandlestick() %>%
dyRangeSelector()
Sys.sleep(1)
}
The problem is that RStudio's viewer is locked while the function runs and the plot is not even displayed when the function returns (I can only manually plot the collected data afterwards). I would want the plot to be displayed at each step. Any idea how to achieve this?
Edit: This function monitors sensors in real time, so it needs to plot at runtime.
The dygraph function uses an HTML widget, so the result needs to be printed to appear in the viewer. Just add %>% print() at the end and the output should appear, i.e.
for (i in 1:400) {
m<-update_values() # Updates values in the dataframe
dygraph(m[,1:4]) %>%
dyCandlestick() %>%
dyRangeSelector() %>%
print()
Sys.sleep(1)
}
However, a disadvantage of this approach is that you'll end up with 400 pages in the viewer. As far as I know there's no way to say to replace the current view, you can just add new ones. Maybe rstudioapi has a "Delete viewer page" function, but I don't see it.
Related
I am trying to use the Export -> Copy to Clipboard option after making a kable() or gt() table. When I go to paste elsewhere, the clipboard image taken is a weird mix of my RStudio background with only part of the table. It is like my computer is clipping the wrong part of my screen. I have double checked and this does not happen when I try to do the same thing with ggplot(). I've attached my code as an example and what I receive as my output. I have instead been saving these plots as images (and this works fine!) but I really don't need these plots/just would like to copy them.
hectare <- PlantGrowth %>%
mutate(hectare = weight/10000)
partbtab <- hectare %>%
group_by(group) %>%
summarise("Mean/Yr" = mean(hectare),
"25 Year Average" = `Mean/Yr`*25)
kable(partbtab) %>%
kableExtra::kable_styling()
#this also does the weird screenshot
gt(partbtab)
This is what the copied "plot" ends up as:
I'm regularly connected to our database, whose data continuously changes. I was wondering if there was a way to run a specific set of lines of code on a regular time interval? For example:
list_table <- as_tibble(mydatabaseconnection %>%
tbl("mytable"))
View(list_table , title = "list_table")
I run this manually every now and then, but it would be nice to have the table on one of my screens and have it update periodically on its own. So far all I've found are tools that automatically run an entire script and you can only view their output as images or excel files. Any way to do what I outlined above within RStudio?
You could use something like Sys.sleep() inside a for loop, e.g.:
for (i in 1:24) {
print(i)
Sys.sleep(5)
}
In this case, it would look like:
for (i in 1:24) {
list_table <- as_tibble(mydatabaseconnection %>%
tbl("mytable"))
View(list_table , title = "list_table")
Sys.sleep(5)
}
I have recently been going through some of the modules on Software Carpentry's "Programming in R" lesson, and I have experienced problems displaying some of my plots in RStudio.
Here is the link to the site:
http://swcarpentry.github.io/r-novice-inflammation/04-cond/index.html
Here is the page with the download link for the inflammation data files (r-novice-inflammation-data.zip) if necessary:
http://swcarpentry.github.io/r-novice-inflammation/setup.html
And the practice problem that I am on is called "Choosing Plots Based on Data"
I was supposed to create a function that creates a box plot or stripchart for a file on patient inflammation data based on whether the vector of that data that is called meets a certain threshold. Here is my code:
dat <- read.csv(file = "data/inflammation-01.csv", header = FALSE)
plot_dist <- function(x, threshold) {
if (length(x) > threshold) {
boxplot(x)
} else {
stripchart(x)
}
}
plot_dist(dat[, 10], threshold = 10)
When I call the function, however, no plots are displayed. I went to the plots section in Rstudio, but still found no plots. On my console, the output after calling this function is something like:
Does anyone have any ideas why my plots aren't being displayed? I don't think there is anything wrong with the function, since I don't get any errors after calling it, it just doesn't plot anything. Thanks much!
Every time I apply View() on any data, it replaces the actual window of data from previous View(). I assume it should be some configuration on Rstudio, but I don't know how and on the internet it's not a common problem.
You can specify the title of the View() window with the title option, e.g.:
View(mtcars, title = "new_window")
Of if you use a pipe:
mtcars %>%
View(., title = "new_window")
Just make sure that your windows have different titles.
I am looking to create a custom function in R that will allow the user to call the function and then it will produce an auto complete pipeline ready for them to edit, this way they can jump into quickly customizing the standard pipeline instead of copy pasting from an old script or retyping. How can I go about setting up this sort of autocomplete:
#pseudo code what I type---
seq.Date(1,2,by = "days") %>%
pblapply(function(x){
read.fst(list.files(as.character(x), as.data.table = T) %>%
group_by(x) %>%
count()
}) %>% rbindlist()
#how can I write a function so that when I call that function, it ouputs an autocomplete
#of the above so that I can go ahead and start just customizing the code? Something like this
my_autocomplete_function = function(x) {
print(
"
seq.Date(as.Date(Sys.Date()),as.Date(Sys.Date()+1),by = 'days') %>%
pbapply::pblapply(function(x){
fst::read.fst(list.files(as.character(x), as.data.table = T)) %>%
#begin filtering and grouping by below custom
group_by()
}) %>% rbindlist()
")
}
#I can just print the function and copy paste the text from the output in my console to my script
my_autocomplete_function()
#but I rather it just autocomplete and appear in the script if possible?
Putting text into the command line will probably be a function of the interface you are using to run R - is it plain R, Rstudio, etc?
One possibility might be to use the clipr package and put the code into the clipboard, then prompt the user to hit their "paste" button to get it on the command line. For example this function which creates a little code string:
> writecode = function(x){
code = paste0("print(",x,")")
clipr::write_clip(code)
message("Code ready to paste")}
Use it like this:
> writecode("foo")
Code ready to paste
Then when I hit Ctrl-V to paste, I see this:
> print(foo)
I can then edit that line. Any string will do:
> writecode("bar")
Code ready to paste
[ctrl-V]
> print(bar)
Its one extra key for your user to press, but having a chunk of code appear on the command line with no prompting might be quite surprising for a user.
I spend my day reading the source code for utils auto completion. The linebuffer only contains the code for ... one line, so that can't do fully what your looking for here, but it is quite customizable. Maybe the rstudio source code for autocompletion has more answers. Here is an example to write and activate your own custom auto completer. It is not well suited for packages as any new pacakge could overwrite the settings.
Below a
#load this function into custom.completer setting to activate
rc.options("custom.completer" = function(x) {
#perhaps debug it, it will kill your rsession sometimes
#browser()
###default completion###
##activating custom deactivates anything else
#however you can run utils auto completer also like this
#rstudio auto completation is not entirely the same as utils
f = rc.getOption("custom.completer")
rc.options("custom.completer" = NULL)
#function running base auto complete.
#It will dump suggestion into mutable .CompletionEnv$comps
utils:::.completeToken() #inspect this function to learn more about completion
rc.options("custom.completer" = f)
###your custom part###
##pull this environment holding all input/output needed
.CompletionEnv = utils:::.CompletionEnv
#perhaps read the 'token'. Also 'linebuffer', 'start' & 'end' are also useful
token = .CompletionEnv$token
#generate a new completion or multiple...
your_comps = paste0(token,c("$with_tomato_sauce","$with_apple_sauce"))
#append your suggestions to the vanilla suggestions/completions
.CompletionEnv$comps = c(your_comps,.CompletionEnv$comps)
print(.CompletionEnv$comps)
#no return used
NULL
})
xxx<tab>
NB! currently rstudio IDE will backtick quote any suggestion which is not generated by them. I want to raise an issue on that someday.
Bonus info: A .DollarNames.mys3class-method can be very useful and works with both rstudio and utils out of the box e.g.
#' #export
.DollarNames.mys3class = function(x, pattern = "") {
#x is the .CompletionEnv
c("apple","tomato")
}