I would like to print a nice formatted table to a graphics device. I am aware there is textplot(), however it seems not to support the tabular() function from the tables package, which I use to assemble my table.
Is there a workaround, maybe another pair of functions that can help me here?
EDIT:
Here is an example of what I am trying to do:
dat <- data.frame(
id=paste("id", 1:10),
loc=sample(c("north", "south"), 10, replace=TRUE),
val1=rnorm(10),
val2=rnorm(10)
)
tab <- tabular(id + 1 ~ (val1 + val2)*loc*sum, data=dat)
#textplot(tab) # won't do it
(The call to tabular will become more complex, I am currently learning it step by step...)
Any hint appreciated! I am now thinking of using text with a monospaced fonts, but maybe there is something better?
EDIT2:
Here is the accepted solution:
textplot(capture.output(tab))
You could use capture.output with the printed form of the tabular output then pass the result to textplot. Or you could convert the result of tabular to a matrix and pass that to the addtable2plot function in the plotrix package.
I've been working on an update of gridExtra::grid.table that would support basic features of tabular(). You can try it:
# requires gtable
library(devtools)
source_gist(2013903)
The only graphics device that I know that would possibly accept LaTeX input is the tikzDevice::tikz. You might want to include the code your are sending to tables::tabular and we could see if the output is handled naturally.
Related
I can see the entire data frame in the console. Is there any possible way or any function to view data frame in the R-Console (Editing similar to that of Excel) so that I should be able to edit the data manually?
S3 method for class 'data.frame'
You can use:
edit(name, factor.mode = c("character", "numeric"),
edit.row.names = any(row.names(name) != 1:nrow(name)), ...)
Example:
edit(your_dataframe)
You can go through in detail with the help of this link - Here
You really can use edit() or view().
But maybe, if you dataset isn't big enough, if you prefer to use Excel, you can use this function below:
library(xlsx)
view.excel<-function(inputDF,nrows=5000){
if (class(inputDF)!="data.frame"){
stop("ERROR: <inputDF> class is not \"data.frame\"")
}
if(nrow(inputDF)>5000 & nrows!=-1){
inputDF=inputDF[1:nrows,]
}
tempPath=tempfile(fileext='.xlsx')
write.xlsx(inputDF,tempPath)
system(paste0('open ',tempPath))
return(invisible(tempPath))
}
I've defined this function to help me with some tasks in R...
Basically, you only need to pass a DataFrame to the function as a parameter. The function by default display a maximum of 5000 rows (you can set the parameter nrows = -1 to view all the rows, but it may be slow).
This function opens your DataFrame in Excel and returns the path where your temporary view was saved. If you wanna save and load your temporary view, after changing something directly with Excel, you can load again your data frame with:
# Open a view in excel
tempPath <- view.excel(initialDF, nrows=-1)
# Load the file of the Excel View in the new DataFrame modifiedDF
modifiedDF <- read.xlsx(tempPath)
This function may works well in Linux, Windows or Mac.
You can view the dataframe with View():
View(df)
As #David Arenburg says, you can also open your dataframe in an editable view, but be warned this is slow:
edit(df)
For updates/changes to affect the dataframe use:
df <- edit(df)
Since a lot of people are using (and developing in) RStudio and Shiny nowadays, things have become far more convenient for R users.
You should look at the rhandsontable package.
There is also very nice Shiny implementation of rhandsontable, from a blog I stumbled upon: https://stla.github.io/stlapblog/posts/shiny_editTable.html. It's not using the console, but it is anyway super slick:
(A few years later) This may be worth trying if you use RStudio: It seems to support all data types. I did not use it extensively but helped me ocassionally:
https://cran.r-project.org/web/packages/editData/README.html
It shows an editing dialog by default. If your dataframe is big you can browse to http://127.0.0.1:7212 while the dialog is being shown, to get a resizable editing view.
You can view and edit a dataframe using with the fix() function:
# Open the mtcars dataframe for editing:
fix(mtcars)
# Edit and close.
# This produces the same result:
mtcars <- edit(mtcars)
# But it is a longer command to write.
Is there an equivalent to the unix less command that can be used within the R console?
There is also page() which displays a representation of an object in a pager, like less.
dat <- data.frame(matrix(rnorm(1000), ncol = 10))
page(dat, method = "print")
Not really. There are the commands
head() and tail() for showing the beginning and end of objects
print() for explicitly showing an object, and just its name followed by return does the same
summary() for concise summary that depends on the object
str() for its structure
and more. An equivalent for less would be a little orthogonal to the language and system. Where the Unix shell offers you less to view the content of a file (which is presumed to be ascii-encoded), it cannot know about all types.
R is different in that it knows about the object types which is why summary() -- as well as the whole modeling framework -- are more appropriate.
Follow-up edit: Another possibility is provided by edit() as well as edit.data.frame().
I save the print output to a file and then read it using an editor or less.
Type the following in R
sink("Routput.txt")
print(varname)
sink()
Then in a shell:
less Routput.txt
If the file is already on disk, then you can use file.show
You might like my little toy here:
short <- function(x=seq(1,20),numel=4,skipel=0,ynam=deparse(substitute(x))) {
ynam<-as.character(ynam)
#clean up spaces
ynam<-gsub(" ","",ynam)
#unlist goes by columns, so transpose to get what's expected
if(is.list(x)) x<-unlist(t(x))
if(2*numel >= length(x)) {
print(x)
}
else {
frist=1+skipel
last=numel+skipel
cat(paste(ynam,'[',frist,'] thru ',ynam,'[',last,']\n',sep=""))
print(x[frist:last])
cat(' ... \n')
cat(paste(ynam,'[',length(x)-numel-skipel+1,'] thru ', ynam, '[', length(x)-skipel,']\n',sep=""))
print(x[(length(x)-numel-skipel+1):(length(x)-skipel)])
}
}
blahblah copyright by me, not Disney blahblah free for use, reuse, editing, sprinkling on your Wheaties, etc.
I am doing java and R integration using JRI.
Please find below script
String path = "C:\\Users\\hrpatel\\Desktop\\CSVs\\DataNVOCT.csv";
rengine.eval("library(tseries)");
rengine.eval(String.format("mydata <- read.csv('%s')",path.replace('\\', '/')));
String exportFilePath= "C:\\Users\\hrpatel\\Desktop\\CSVs\\arima3.jpg";
rengine.eval("Y <- NewVisits");
rengine.eval("t <- Day.Index");
rengine.eval("summary(Y)");
rengine.eval("adf.test(Y, alternative='stationary')");
rengine.eval("adf.test(Y, alternative='stationary', k=0)");
rengine.eval("acf(Y)");
rengine.eval("pacf(Y)");
rengine.eval("mydata.arima101 <- arima(Y,order=c(1,0,1))");
rengine.eval("mydata.pred1 <- predict(mydata.arima101, n.ahead=1000)");
rengine.eval(String.format("jpeg('%s')",exportFilePath.replace('\\', '/')));
rengine.eval("plot(t,Y)");
rengine.eval("lines(mydata.pred1$pred, col='blue',size=10)");
rengine.eval("lines(mydata.pred1$pred+1*mydata.pred1$se, col='red')");
rengine.eval("lines(mydata.pred1$pred-1*mydata.pred1$se, col='red')");
rengine.eval("dev.off()");
In above codebase when i tried plot(t,Y) or plot(Y). it export a blank image, while in case of plot(mydata) it is working file.
One more thing when i run above code in R it creates the image(using JRI it shows blank image).
I have spend 1 day to solve this but i dont found any solution.
Please suggest if you have any alternatives.
Your help is needed.
Thanks in Advance
if i understand correctly, you have a data set named mydata, that has two columns, NewVisits, and Day.Index, in that case you need to change:
rengine.eval("Y <- NewVisits");
to
rengine.eval("Y <- mydata$NewVisits");
and
rengine.eval("t <- Day.Index");
to
rengine.eval("t <- mydata$Day.Index");
This also explains why plot(mydata) works for you - because R recognizes it.
if this isn't the solution, then i cant see where you are reading NewVisits and Day.Index from
BTW i stongly recommend to plot using the ggplot package
I wish to read data into R from SAS data sets in Windows. The read.ssd function allows me to do so, however, it seems to have an issue when I try to import a SAS data set that has any non-alphabetic symbols in its name. For example, I can import table.sas7bdat using the following:
directory <- "C:/sas data sets"
sashome <- "/Program Files/SAS/SAS 9.1"
table.df <- read.ssd(directory, "table", sascmd = file.path(sashome, "sas.exe"))
but I can't do the same for a table SAS data set named table1.sas7bdat. It returns an error:
Error in file.symlink(oldPath, linkPath) :
symbolic links are not supported on this version of Windows
Given that I do not have the option to rename these data sets, is there a way to read a SAS data set that has non-alphabetic symbols in its name in to R?
Looking about, it looks like others have your problem as well. Perhaps it's just a bug.
Anyway, try the suggestion from this (old) R help post, posted by the venerable Dan Nordlund who's pretty good at this stuff - and also active on SASL (sasl#listserv.uga.edu) if you want to try cross-posting your question there.
https://stat.ethz.ch/pipermail/r-help/2008-December/181616.html
Also, you might consider the transport method if you don't mind 8 character long variable names.
Use:
directory <- "C:/sas data sets"
sashome <- "/Program Files/SAS/SAS 9.1"
table.df <- read.ssd(library=directory, mem="table1", formats=F,
sasprog=file.path(sashome, "sas.exe"))
I am using tableNominal{reporttools} to produce frequency tables. The way I understand it, tableNominal() produces latex code which has to be copied and pasted onto a text file and then saved as .tex. But is it possible to simple export the table produced as can be done in print(xtable(table), file="path/outfile.tex"))?
You may be able to use either latex or latexTranslate from the "Hmisc" package for this purpose. If you have the necessary program infrastructure the output gets sent to your TeX engine. (You may be able to improve the level of our answers by adding specific examples.)
Looks like that function does not return a character vector, so you need to use a strategy to capture the output from cat(). Using the example in the help page:
capture.output( TN <- tableNominal(vars = vars, weights = weights, group = group,
cap = "Table of nominal variables.", lab = "tab: nominal") ,
file="outfile.tex")