separate screen for output in R? - r

I am using RStudio for my project, I want a separate screen for the output. I tried with sink(), but I need a new pop up window. My code is
vd<-data.frame()
vd<-c("V1","V2")
vf<-length(vd)
i<-1
while(i<=vf){
vd<-c("V1","V2")
#print(vd)
leng<-length(vd)
selectru<-combn(vd,leng)
#print(selectru)
print(selectru[i])
fst<-selectru[i]
select<-data.frame()
select<-selectru[selectru[,1]!=selectru[i],]
m<-length(select)
select<-combn(select,m)
snd <-apply(select,2,function(rows) paste0(rows, collapse = ""))
cat(sprintf("\"%s\" =>\"%s\"\n", fst,snd))
i<-i+1
}
These data is not the actual one, just example data.
Is it possible to show the output "ONLY" in a separate screen or browser window? no need to show any graph or plot operation.

Per my comment, here's an example using the sinkstart function from rite.
Code:
library(rite)
sinkstart(echo=FALSE)
# your code
# close the widget with the X or
# use `sinkstop()` to turn off the `sink`ing
Here's a screenshot:

Related

Multiple altair charts generated by the same cell

I have a list of pandas dataframes I named entries, which I want to visualize after running code from the same cell. Below is the code I used :
alt.data_transformers.disable_max_rows()
for entry in entries :
entry['ds'] = entry.index
entry['y'] = entry['count']
entry['floor'] = 0
serie = alt.Chart(entry).mark_line(size=2, opacity=0.7, color = 'Black').encode(
x=alt.X('ds:T', title ='date'),
y='y'
).interactive().properties(
title='Evolution of '+entry.event.iloc[0]+' events over time'
)
alt.layer(serie)\
.properties(width=870, height=450)\
.configure_title(fontSize=20)
When i run the same code out of the 'for' loop, I get to see the one chart that corresponds to one dataframe, but once I run the code above, I don't get any graphs at all.
Does anyone know why It's not working or how to solve this issue?
TLDR: use chart.display()
Unless a chart appears at the end of the cell, you must manually display it.
By analogy, if you run
x + 1
by itself, Python will display the result. However, if you run
for x in range(10):
x + 1
Python will not display anything, because the last statement in the cell (in this case the for loop) has no return value to display. Instead you have to write
for x in range(10):
print(x + 1)
For altair, the mechanism is similar: if the chart is defined in the last statement in the cell, it will be automatically displayed. Otherwise, you have to manually trigger the display, which you can do using the display method:
for i in range(10:
chart = alt.Chart(...)
chart.display()
For more information on display troubleshooting in Altair, see https://altair-viz.github.io/user_guide/troubleshooting.html

print entire string to console without truncating and without adjusting a global setting

I have read these SO posts on getting rstudio to print out without truncating:
list output truncated - How to expand listed variables with str() in R
avoid string printed to console getting truncated (in RStudio)
The answers there involve making a adjustment to studio settings which would then cover all future outputs to the console.
Is there a ad hoc way to get r to print an entire string to the console?
I tried:
library(tidyverse)
library(foreach)
mystring <- foreach(i = 1:52) %do% {
paste0("'_gaWeek",i,"'!A16:B;")
} %>% unlist %>% toString()
print(mystring, len = length(mystring))
> print(mystring, len = length(mystring))
[1] "'_gaWeek1'!A16:B;, '_gaWeek2'!A16:B;, '_gaWeek3'!A16:B;, '_gaWeek4'!A16:B;, '_gaWeek5'!A16:B;, '_gaWeek6'!A16:B;, '_gaWeek7'!A16:B;, '_gaWeek8'!A16:B;, '_gaWeek9'!A16:B;, '_gaWeek10'!A16:B;, '_gaWeek11'!A16:B;, '_gaWeek12'!A16:B;, '_gaWeek13'!A16:B;, '_gaWeek14'!A16:B;, '_gaWeek15'!A16:B;, '_gaWeek16'!A16:B;, '_gaWeek17'!A16:B;, '_gaWeek18'!A16:B;, '_gaWeek19'!A16:B;, '_gaWeek20'!A16:B;, '_gaWeek21'!A16:B;, '_gaWeek22'!A16:B;, '_gaWeek23'!A16:B;, '_gaWeek24'!A16:B;, '_gaWeek25'!A16:B;, '_gaWeek26'!A16:B;, '_gaWeek27'!A16:B;, '_gaWeek28'!A16:B;, '_gaWeek29'!A16:B;, '_gaWeek30'!A16:B;, '_gaWeek31'!A16:B;, '_gaWeek32'!A16:B;, '_gaWeek33'!A16:B;, '_gaWeek34'!A16:B;, '_gaWeek35'!A16:B;, '_gaWeek36'!A16:B;, '_gaWeek37'!A16:B;, '_gaWeek38'!A16:B;, '_gaWeek39'!A16:B;, '_gaWeek40'!A16:B;, '_gaWeek41'!A16:B;, '_gaWeek42'!A16:B;, '_gaWeek43'!A16:B;, '_gaWeek44'!A16:B;, '_gaWeek45'!A16:B;, '_gaWeek46'!A16:B;, '_gaWeek47'!A16:B;, '_gaWeek48'!A16:B;, '_gaWeek49'!A16:B;, '_gaWeek50'!A16:B;, '_ga... <truncated>
It's truncated. Is there an ad hoc way around this without changing rstudio settings? Such as by a function argument? I tried print() here.
Also, how do I get rid of the comma separator in between each instance above?
The short answer is "no" since, the option limiting the print is in the IDE itself, which you can't control from your program itself (I'm assuming you're not some crazy hacker here), and not a language feature. It's like trying to stop "WINDOWS" from doing things (although not).
Seems to me the easiest way (ad hoc) is to turn it on, do whatever, then turn it off. If you insist on not doing that, you need to write your own function:
myprint<- function(somestring,idelimit=100) {
for(i in seq(1,nchar(somestring),idelimit+1)) {
print(substr(somestring,i,i+idelimit));
}
}
I'm not a fluent R coder so let me know if you catch a syntax error. The idea is simple - idelimit should be wherever studio truncates (I chose 100 arbitrarily), and basically you're doing the splitting yourself so string is printed line after line without truncation. Each time you take a portion at most idelimit long from somestring and print it.

Text Editor Won't Close and Crashes in R

I am trying to run a model in R using PVA and transition matrices. Whenever I run a line and the text editor spreadsheet pops up, I am able to edit the data but it won't close and just freezes so I have to shut everything down. I've tried restarting several times but I can't get it to work and I need to be able to run this line of code. Specifically it happens when I run "supplement_matrix <- make.supplement.matrix(num.stages)" Here is my code:
library(popbio)
library(reshape2)
library(expm)
multiyear.stages <- read.csv('multiyear_stages_longform.csv')
head(multiyear.stages)
unique(multiyear.stages$Survey)
nrow(multiyear.stages[multiyear.stages$Survey==1,])
nrow(multiyear.stages[multiyear.stages$Survey==1&multiyear.stages$Stage==1,])
nrow(multiyear.stages[multiyear.stages$Survey==2,])
nrow(multiyear.stages[multiyear.stages$Survey==2&multiyear.stages$Stage==2,])
nrow(multiyear.stages[multiyear.stages$Survey==1&multiyear.stages$Stage<=2,])
nrow(multiyear.stages[multiyear.stages$Survey<=2&multiyear.stages$Stage==1,])
nrow(multiyear.stages[multiyear.stages$Survey==2&multiyear.stages$Stage==2,])
plants<-dcast(multiyear.stages, ID~Survey, value.var="Stage", fill=-1,
fun.aggregate=mean)
head(plants)
nrow(plants[plants$"1"==1&plants$"2"==2,])
nrow(plants[plants$"1"==1&plants$"2"==0,])
nrow(plants[plants$"1"==1&plants$"2"==1,])
nrow(plants[plants$"1"==1&plants$"2"==3,])
nrow(plants[plants$"1"==2&plants$"2"==0,])
nrow(plants[plants$"1"==2&plants$"2"==1,])
nrow(plants[plants$"1"==2&plants$"2"==2,])
nrow(plants[plants$"1"==2&plants$"2"==3,])
nrow(plants[plants$"1"==3&plants$"2"==1,])
nrow(plants[plants$"1"==3&plants$"2"==2,])
nrow(plants[plants$"1"==3&plants$"2"==3,])
nrow(plants[plants$"2"==-1&plants$"3"==1,])
nrow(plants[plants$"2"==1&plants$"3"==0,])
nrow(plants[plants$"2"==1&plants$"3"==1,])
nrow(plants[plants$"2"==1&plants$"3"==2,])
nrow(plants[plants$"2"==1&plants$"3"==3,])
nrow(plants[plants$"2"==2&plants$"3"==0,])
nrow(plants[plants$"2"==2&plants$"3"==1,])
nrow(plants[plants$"2"==2&plants$"3"==2,])
nrow(plants[plants$"2"==3&plants$"3"==3,])
nrow(plants[plants$"2"==3&plants$"3"==0,])
nrow(plants[plants$"2"==3&plants$"3"==1,])
nrow(plants[plants$"2"==3&plants$"3"==2,])
nrow(plants[plants$"2"==3&plants$"3"==3,])
nrow(plants[plants$"1"==3,])
A<-cbind(c(0.317,0.384,0.017), c(0.071,0.592,0.195), c(0.02,0.76,0.1))
N0<-c(40,136,38)
N0 %*% A
source('PVA_source.R')
num.stages<-3
num.iter<-50
num.years<-50
num.iter<-10
num.years<-10
quasi_extinction_threshold<-10
carrying_capacity<-1000
number_of_plants_in_year_1_Stage1 <-cbind(c(19), c(12), c(1))
transition_matrix<-cbind(c(0.317,0.384,0.017), c(0.071,0.592,0.195),
c(0.02,0.76,0.1))
fertility <- c(2.475)
supplement_matrix <- make.supplement.matrix(num.stages)
Here are links to the data I'm using
https://drive.google.com/file/d/0BwRwgnqxDOlxUWNyS25FYVpOZFk/view?usp=sharing
https://drive.google.com/file/d/0BwRwgnqxDOlxZXUzX2EwM2NOZEU/view?usp=sharing
It's hard to diagnose the problem, because I can't replicate it (it runs fine for me). However, you can work around it.
Here's the function from that PVA script that's freezing your system:
make.supplement.matrix<-function(num.stages){
supplement <- matrix(0,nrow=num.stages,,ncol=1,
dimnames=list(paste('stage',1:num.stages),'Number of extra plants to plant each year')
)
supplement <- edit(supplement)
supplement
}
Instead of using it, why not just run:
supplement <- matrix(0,nrow=num.stages,,ncol=1,
dimnames=list(paste('stage',1:num.stages),'Number of extra plants to plant each year')
)
then manually edit (in your script or interactive console) the matrix called supplement any way you please?

Can you unprint a line in R?

I am writing up some data processing stuff and I wanted to have a concise progress status printing a fraction that updates over time on a single line in the console.
To get this done I wanted to have something like this
print(Initiating data processing...)
for(sample in 1:length(data)){
print(paste(sample,length(data),sep="/"))
process(data[[sample]])
#Unprint the bottom line in the console ... !!! ... !!!.. ?
}
Keeping the screen clean and what not. I don't quite know how to do it. I know that there is a R text progress bar but for utilities sake I'm looking for a little more control.
Thanks!
I think your best bet is to do exactly what the R text progress bar does, which is "\r to return to the left margin", as seen in the help file. You'll have to use cat instead of print because print ends with a newline.
cat("Initiating data processing...\n")
for(sample in 1:length(data)){
cat(sample, length(data), sep="/")
process(data[[sample]])
cat("\r")
}
cat("\n")

Programmatically close the window created by `View(x)`

I'm viewing a dataframe in R using View:
my_df <- data.frame(a=1:10, b=letters[1:10])
View(my_df)
I'd like to now close the resulting window programmatically (rather than clicking the X button).
How may I do this? graphics.off doesn't work as it isn't a graphics device. Looking at the View code, internal function dataviewer is used to display the window but I'm not sure what it uses in the background (tcltk?) so am not sure how to close the window.
Re some comments as to why I want this.
I'm basically doing a user-checking step in a script whereby the user is asked if a snippet of a dataframe and a corresponding image go together. It goes something like this:
for (i in 1:heaps) {
1. View(a snippet of a big dataframe)
2. show an image
3. readline('Is this OK? [Y/N]: ') (store the i for which it's not OK)
4. close the image window (graphics.off()), close the View(..) window.
}
I basically wanted to reduce the user interaction down staring at the image & dataframe snippet and typing Y or N, so they don't have to manually close th dataframe window for each i in the loop.
(I'm part-way through this validation myself and am dealing with 200 View(snippet) windows that I haven't bothered to close D:. Also, have noticed that the opening of the windows steals keyboard focus away from the prompt so me typing Y/N is not as fast as I'd like. But I only have to do this once, so it'll do for now. I am curious as to the answer to the question though, for next time).
One way to accomplish what you're after is to make use of the system function. You could, for example, determine the Window ID/Name and then issue a close command like so:
system('(sleep 10; wmctrl -c "Data: my_df") &')
The above command will wait 10 seconds, and then issue a command to the window manager to close any window with the name "Data: my_df". These 2 commands are wrapped in parens. This is known as a Compound Command in bash. The entire Compound Command is backgrounded, '&'.
I tested the following and it worked:
# sample1.R
my_df <- data.frame(a=1:10, b=letters[1:10])
system('(sleep 10; wmctrl -c "Data: my_df") &')
View(my_df)
Another way to accomplish this is like so:
# sample2.R
my_df <- data.frame(a=1:10, b=letters[1:10])
View(my_df)
system('read -p "Press [Enter] key to start backup..."')
my_df2 <- data.frame(a=1:10, b=letters[1:10])
View(my_df2)
system('read -p "Press [Enter] key to start backup..."')
I'm running these like this:
R CMD BATCH sample2.R
NOTE: The prompt from the read -p command isn't showing up in my terminal but you could just print a duplicate prompt message in R.
If you want to close all open "View" windows, building on the answer of slm :
CloseViews <- function(){
cmd <- paste0('wmctrl -c "Data:" -v')
ok <- TRUE
while(ok){
out <- suppressWarnings(system(cmd,intern=TRUE,ignore.stderr=TRUE))
Sys.sleep(0.2)
ok <- is.null(attr(out,"status"))
print(ok)
}
}
Then CloseViews() does the trick, which I found particularly helpful when working interactively.

Resources