DSCI 325: Handout 28 – Introduction to R Markdown Spring 2017

Total Page:16

File Type:pdf, Size:1020Kb

DSCI 325: Handout 28 – Introduction to R Markdown Spring 2017 DSCI 325: Handout 28 – Introduction to R Markdown Spring 2017 R Markdown provides a mechanism to create dynamic documents with embedded chunks of R code. This allows you to keep your R code, your outputs (e.g., summaries and/or graphs), and your discussion/comments all in the same document. Subsequently, you can produce nicely formatted output in html, pdf, or Microsoft Word. The following website gives more information about R Markdown: http://rmarkdown.rstudio.com/. CREATING A NEW R MARKDOWN DOCUMENT In R Studio, select File > New File > R Markdown. Tell R Studio that you want to create a new html Document, and fill in the Title and Author fields. When you click OK, a sample script containing R Markdown code appears in R studio. Select File > Save As… to save this script in your own desired directory. Next, select “Knit HTML” to create the html file. 1 Note that a webpage appears. This webpage includes the title and author information, the date, R code, R output, and comments/discussion. If you close this webpage, you can access it once again from the directory in which you saved your R Markdown (.Rmd) file. WRITING A NEW R MARKDOWN DOCUMENT Let’s start with the sample R script. Leave the metadata section that includes the title, author, date, and output information (you can modify these if you want); delete all other comments/code from the sample script. Next, write a line of text in the file, similar to the following. Adding R Code Chunks Suppose we wanted to create a plot with the dotplot() function from the lattice library. Try adding the following commands to your R Markdown script. 2 When you click on “Knit HTML” to create the webpage, the following is returned: Note that R treated the commands as text. To separate code from comments/text, you must use a code separator. The easiest way to accomplish this in R Studio is to “Insert a new code chunk” as shown below. This adds the following to your script. The three backticks followed by {r} separates R code from text. Once you have entered your R commands inside the code chunk, your script should appear as follows: 3 Now, when you click on “Knit to HTML” to create the webpage, the following is returned: Now, you can see that the html file contains all of the following: The title/author/date/information Text/comments from the author R commands (which are nicely highlighted) R output Next, suppose that one line of the R script was changed, as is shown below. 4 Now, when you click on “Knit HTML” you will see that messages normally sent to the R console are also included in the document produced by R Markdown. Suppressing Messages If you want to suppress messages from being sent to the final document, you can use the message=FALSE option in the code chunk that you want to suppress. ```{r message=FALSE} require(lattice) NutritionData = read.csv("T:/20165001682/ReadOnly/Data/NutritionData.csv") attach(NutritionData) dotplot(Location ~ SatFat,xlab="Saturated Fat") ``` Suppressing R Code to Display Only Output If you want to suppress the R code in your final report, use the echo=FALSE option. ```{r message=FALSE, echo=FALSE} require(lattice) NutritionData = read.csv("T:/20165001682/ReadOnly/Data/NutritionData.csv") attach(NutritionData) dotplot(Location ~ SatFat,xlab="Saturated Fat") ``` The html document now appears as follows. 5 Changing the Plot Size If you aren’t satisfied with the size of the plot relative to the text, you can use the fig.width and fig.height options. For example, consider the following. ```{r message=FALSE, echo=FALSE, fig.height=3.5, fig.width=4.5} require(lattice) NutritionData = read.csv("T:/20165001682/ReadOnly/Data/NutritionData.csv") attach(NutritionData) dotplot(Location ~ SatFat,xlab="Saturated Fat") ``` 6 Writing Inline Code Instead of inserting a code chunk, you can also surround code with back ticks (start the code with the letter r). R will replace the inline code with its results when the final document is created. The overall mean sodium level of the menu items from McDonald's was `r mean(NutritionData[Location=="McDonalds","Sodium"])`. R returns the following in the html document: The Basics of Text Formatting in R Markdown Note how the following R Markdown syntax was used to format text in the document. Headers (Could also be used to create sections and subsections) Markdown Syntax Formatted Text # Header 1 ## Header 2 ### Header 3 Block Quotes Markdown Syntax Formatted Text This is a test to see block quotes. > Block quote is shown here. Bulleted Lists Markdown Syntax Formatted Text * Item 1 * Item 1a * Item 1b * Item 2 * Item 2a * Item 2b 7 Italics Markdown Syntax Formatted Text Use the *asterisk* to italicize text. Boldface Markdown Syntax Formatted Text Use two asterisks to get **boldface**. Typewriter Form Markdown Syntax Formatted Text Use the `backtick` for typewriter face text. Subcripts/Superscripts Markdown Syntax Formatted Text $Subcript_1$ $Superscript^1$ New paragraphs (end a line with two spaces to start a new paragraph). Markdown Syntax Formatted Text Test 1 Test 2 Test 1 Test 2 Hyperlinks Markdown Syntax Formatted Text [link](https://www.rstudio.com/) 8 Inline Equations Markdown Syntax Formatted Text The area of a circle is $A = \pi*r^{2}$ Consider the following script to see how some of the formatting works. --- title: "Fast Food Nutrition Data" author: "Tisha Hooks" date: "April 25, 2016" output: html_document --- ```{r warning=FALSE, message=FALSE, echo=FALSE} library(lattice) library(dplyr) NutritionData = read.csv("T:/20175002183/ReadOnly/Data/NutritionData.csv") attach(NutritionData) ``` This report summarizes nutrition data from several fast food restaurants. The data can be found on our course storage space in the file *NutritionData.csv*. The following response variables will be considered. * Calories * Saturated Fat * Cholesterol * Sodium For each response variable, summary statistics will be computed **by restaurant** using the `by()` and `summary()` functions. A dotplot will also be created so that comparisons can be made across restuarants. ## Summary of Calories by Restaurant ```{r fig.height = 3, fig.width=6} by(Calories, Location, summary) dotplot(Location ~ Calories, xlab="Calories") ``` ## Summary of Saturated Fat by Restaurant ```{r, echo=FALSE, fig.height = 3, fig.width=6} by(SatFat, Location, summary) dotplot(Location ~ SatFat, xlab="Saturated Fat") ``` ## Summary of Cholesterol by Restaurant ```{r, echo=FALSE, fig.height = 3, fig.width=6} by(Cholesterol, Location, summary) dotplot(Location ~ Cholesterol, xlab="Cholesterol") ``` 9 ## Summary of Sodium by Restaurant ```{r, echo=FALSE} by(Sodium,Location,summary) dotplot(Location ~ Sodium,xlab="Sodium") Rendering Your Report The easiest way to render the report is to click the “Knit to HTML” button at the top of the R Studio scripts pane. When you render the report, R executes the code and builds a new version of your report in the output file type you requested (you can change this to “Knit to PDF,” for example). R will also open a preview of the output file in the viewer pane and save the output file in your working directory. 10 .
Recommended publications
  • Rich Text Editor Control in Asp Net
    Rich Text Editor Control In Asp Net Ginger te-heed his Manaus orchestrating tolerantly, but high-tension Peirce never recirculated so amazingly. Empathetic lemuroidOlin inarches Iggie bellicosely communizing while some Wait sipper always so rule open-mindedly! his exodes aggrandizing obliquely, he master so manfully. Dietetical and Find and rich text control is dependent on mobile applications which will be renamed to the asp. Net rich text editors and when working on mobile development and size can controls in. This tutorial help. Numerous optimization methods have been applied. Net ajax saving for controlling the editors, it only the access database in. Moving forward, we will see how this editor can be used in ASP. ASPNET WYSIWYG rich HTML editor for WebForms MVC and all versions of working Framework. Many formats, including HTML. Output jpeg and png picture in original format reducing file sizes substantially. Providing a Richer Means for Entering Text Data. Rich Text Editor for aspnet is by yet the fastest cleanest most powerful online wysiwyg content editor It's also project for PHP and ASP It enables aspnet web developers to clean any textboxtextarea with an intuitive word-like wysiwyg editor. Any form elements appear in kendo ui features are used to select. Use the sublime text editor control hero Power Apps Power Apps. For controlling the control into another way to your desired width. Rich Text Editor is from award-winning UI control that replaces a standard HTML. Add love to TINYMCE Editor TextBox using jQuery Uploadify Plugin in ASP. Read below for it appear showing in my aim is important for! Lite version is free.
    [Show full text]
  • Text Formatting with LATEX, Eclipse and SVN
    Formatting Text LATEX DEMO LATEX beamer Text Formatting with LATEX, Eclipse and SVN Desislava Zhekova CIS, LMU [email protected] July 1, 2013 Desislava Zhekova Text Formatting with LATEX, Eclipse and SVN Formatting Text LATEX DEMO LATEX beamer Outline 1 Formatting Text Text Editor vs. Word Processor What You See Is What You Get 2 LATEX What is LATEX? Microsoft Word vs LATEX Eclipse & SVN 3 DEMO Document Classes Document Class Options Basics Style Files/Packages LATEX for Linguists 4 LATEX beamer Desislava Zhekova Text Formatting with LATEX, Eclipse and SVN http://en.wikipedia.org/wiki/Comparison_of_text_editors Formatting Text LATEX Text Editor vs. Word Processor DEMO What You See Is What You Get LATEX beamer Text Editor vs. Word Processor Text Editors used to handle plain text (a simple character set, such as ASCII, is used to represent numbers, letters, and a small number of symbols) the only non-printing characters they support are: newline, tab, and form feed Desislava Zhekova Text Formatting with LATEX, Eclipse and SVN Formatting Text LATEX Text Editor vs. Word Processor DEMO What You See Is What You Get LATEX beamer Text Editor vs. Word Processor Text Editors used to handle plain text (a simple character set, such as ASCII, is used to represent numbers, letters, and a small number of symbols) the only non-printing characters they support are: newline, tab, and form feed http://en.wikipedia.org/wiki/Comparison_of_text_editors Desislava Zhekova Text Formatting with LATEX, Eclipse and SVN Formatting Text LATEX Text Editor vs. Word Processor DEMO What You See Is What You Get LATEX beamer Text Editors Notepad Bundled with Microsoft Windows Desislava Zhekova Text Formatting with LATEX, Eclipse and SVN Formatting Text LATEX Text Editor vs.
    [Show full text]
  • Microsoft Office Word 2003 Rich Text Format (RTF) Specification White Paper Published: April 2004 Table of Contents
    Microsoft Office Word 2003 Rich Text Format (RTF) Specification White Paper Published: April 2004 Table of Contents Introduction......................................................................................................................................1 RTF Syntax.......................................................................................................................................2 Conventions of an RTF Reader.............................................................................................................4 Formal Syntax...................................................................................................................................5 Contents of an RTF File.......................................................................................................................6 Header.........................................................................................................................................6 Document Area............................................................................................................................29 East ASIAN Support........................................................................................................................142 Escaped Expressions...................................................................................................................142 Character Set.............................................................................................................................143 Character Mapping......................................................................................................................143
    [Show full text]
  • Revisiting XSS Sanitization
    Revisiting XSS Sanitization Ashar Javed Chair for Network and Data Security Horst G¨ortzInstitute for IT-Security, Ruhr-University Bochum [email protected] Abstract. Cross-Site Scripting (XSS) | around fourteen years old vul- nerability is still on the rise and a continuous threat to the web applica- tions. Only last year, 150505 defacements (this is a least, an XSS can do) have been reported and archived in Zone-H (a cybercrime archive)1. The online WYSIWYG (What You See Is What You Get) or rich-text editors are now a days an essential component of the web applications. They allow users of web applications to edit and enter HTML rich text (i.e., formatted text, images, links and videos etc) inside the web browser window. The web applications use WYSIWYG editors as a part of comment functionality, private messaging among users of applications, blogs, notes, forums post, spellcheck as-you-type, ticketing feature, and other online services. The XSS in WYSIWYG editors is considered more dangerous and exploitable because the user-supplied rich-text con- tents (may be dangerous) are viewable by other users of web applications. In this paper, we present a security analysis of twenty five (25) pop- ular WYSIWYG editors powering thousands of web sites. The anal- ysis includes WYSIWYG editors like Enterprise TinyMCE, EditLive, Lithium, Jive, TinyMCE, PHP HTML Editor, markItUp! universal markup jQuery editor, FreeTextBox (popular ASP.NET editor), Froala Editor, elRTE, and CKEditor. At the same time, we also analyze rich-text ed- itors available on very popular sites like Twitter, Yahoo Mail, Amazon, GitHub and Magento and many more.
    [Show full text]
  • A Brief LATEX Tutorial
    A brief LATEX tutorial. Henri P. Gavin Department of Civil and Environmental Engineering Duke University Durham, NC 27708{0287 [email protected] September 30, 2002 Abstract LATEX is a very powerful text processing system available to all students through the university's network of Unix work stations. Versions of LATEX which run on PC's and Mac's are available through the Internet. LATEX is becoming the \standard" text processor for publications in science, engineering, and mathematics. LATEX has many features, including: • The printed output is BEAUT IFUL! • Equations are relatively easy to enter, once you get the hang of it. • LATEX automatically numbers the sections, subsections, figures, tables, footnotes, equations, theorems, lemmas, and the references of your paper. When you add a new section or sub-section, or a new reference, every item is re-numbered au- tomatically! It can create its own table of contents and indices automatically as well. • It can easily manage very long documents, like theses and books. The down-side of LATEX is that it is somewhat cumbersome to use and can be difficult to learn. Many LATEX manuals are not written for the rank beginner, and don't make it terribly clear how to make simple formatting changes such as margins, font size, or line spacing. For many people, learning LATEX through examples is the easiest way to go. The purpose of this document is to illustrate what LATEX can do for you, and (without getting into too much detail) show you how to do it, so that you can learn to use LATEX quickly and easily.
    [Show full text]
  • LATEX Quick Start a first Guide to Document Preparation
    Thomas E. Price Lance Carnes LATEX Quick Start A first guide to document preparation Published by Personal TEX, Inc. First Edition, September 2009. Personal TEX Inc. E-mail/Internet: [email protected] • www.pctex.com Notices: Information in this manual is subject to change without notice and does not represent a commitment on the part of Personal TEX Inc. (PTI). PTI makes no represen- tation, express or implied, with respect to this documentation or the software it describes, including without limitations, any implied warranties of merchantability or fitness for a particular purpose, all of which are expressly disclaimed. PTI shall in no way be liable for any indirect, incidental, or consequential damages. No part of this manual may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying and recording, for any purpose, without the express written permission of Personal TEX Inc. Copyright c 2009 by Personal TEX Inc. All rights reserved. Printed in the United States of America. PCTEX, PCTEX for Windows, and Personal TEX, Inc. are registered trademarks of Personal TEX, Inc. PostScript is a registered trademark of Adobe Systems, Inc. TEX is a trademark of the American Mathematical Society (AMS). MathTıme is a trademark of Publish or Perish, Inc. Lucida R is a trademark of Bigelow & Holmes, Inc. All other brand, product, and trade names are the trademarks of their respective owners. Library of Congress Cataloging-in-Publication Data Price, Thomas E. LaTeX Quick Start : A first guide to document preparation / Thomas E. Price and Lance Carnes. p. cm. Includes bibliographical references.
    [Show full text]
  • Enhancing RTF Output with RTF Control Words and In-Line Formatting
    Paper PO04 Enhancing RTF Output with RTF Control Words and In-Line Formatting Lori S. Parsons, Ovation Research Group, Seattle, Washington ABSTRACT The SAS® Output Delivery System (ODS) allows output to be printed directly to a Rich Text Format (RTF) file. RTF can be read by word processors such as Microsoft Word and WordPerfect. In SAS 8.1, options were added to enhance SAS TITLES and FOOTNOTES. Also added was the ability to use RTF control words within cells. In SAS 8.2, ODS supported in-line formatting and added the TEXT= option. All of these formatting methods give us the ability to insert formatting text into a cell or paragraph and can be used to enhance output. In this paper, an RTF file will be created with enhanced SAS TITLES, footnote markers in variable labels and values, custom footnotes, an inserted image, and an inserted hyperlink. The code was run with SAS Version 9.1.2 on Windows XP Professional. The RTF files are viewed with Microsoft® Office Word 2003. INTRODUCTION Rich Text Format (RTF) is a file type used to transfer formatted text and graphics between applications, even those that run on different platforms such as Windows, IBM and Macintosh. With RTF, documents created under different operating systems and with different software applications can be transferred between those operating systems and applications. It has become increasingly popular to produce output in SAS and then distribute it to others who will view the file in a word processor. Being able to customize SAS output through RTF code is an invaluable tool.
    [Show full text]
  • DP LATEX Formatting Guidelines, Particularly Fig
    Distributed Proofreaders LATEX Formatting Manual August 2012 Contents 1 Overview1 1.1 The DP Process . .1 1.2 For New LATEXers . .3 2 Guidelines7 2.1 Formatting Text . .7 2.2 Formatting Mathematics . 13 2.3 Aligned Material . 19 1 Overview This manual contains guidelines for volunteers at Distributed Proofreaders who format projects using the typesetting languageLATEX. It's geared toward a variety of back- grounds: those who have proofed and formatted thousands of pages at DP but have always avoided LATEX, long-time LATEX users who are fairly new to DP and its ways, and (it is hoped) everyone in between. In the interest of brevity, this manual discusses only well-standardized, project- independent formatting, and cautions mostly against common errors. Frequently, where formatting decisions are concerned, you're directed to external resources (especially, writing to dp-feedback or posting in the forums). Section1 is a very brief introduction to DP, L ATEX, and their distinctive inter- relationship. Section2 constitutes a user's guide and reference manual, meant both to be read for tutorial information and to be thumbed through as you format your first pages. Both parts are written in mostly-independent sections, culled from existing DP wiki pages, forum posts, and private discussions. Do feel free to skip around as you read.1 Important items (such as reminders to ask for human help) are repeated as necessary so they won't be overlooked by non-serial readers, and potential pitfalls are clearly marked. 1.1 The DP Process A book's contents go through three major stages at Distributed Proofreaders: proof- reading (\proofing”), formatting (\F1 and F2"), and post-processing (\PP").
    [Show full text]
  • WYSIWYG Formatted Text & Images Editor for VCL & Firemonkey
    TMS WYSIWYG text editor controls for VCL & FireMonkey WYSIWYG formatted text & images editor for VCL & FireMonkey Background The standard rich text editor that ships with Delphi for over 15 years now is based on the Windows riched20.dll library control. While Microsoft introduced meanwhile newer versions 3.0 and 4.1 of this rich editor control, the VCL version continued to be based on a wrapper of the v2.0. This means that the feature set of this rich editor control is quite limited. On the other side, in the Delphi cross platform framework FireMonkey, there is no edit control for rich text at all. The only editor control that is available there in the framework is TMemo. As many of our customers requested both more flexibility from a Windows VCL based rich editor and also a rich editor for FireMonkey, the TMS team decided to take on these projects. From the start, we want to create a control for FireMonkey that would fit neatly the FMX paradigm of one source code to rule all platforms (Windows, iOS, Android, Mac OSX at this time) but realizing this would be a huge effort, we wanted that this effort would also be usable for VCL developers targetting Windows only. Architecture After a lot of research was done on performance (as we knew from our experience with other FMX controls this would be difficult) we decided on what we internally disrespectfully call a sandwich architecture. This sandwich architecture should enable us to isolate a core formatted text handling layer from the framework, i.e.
    [Show full text]
  • Html Rich Text Editor
    Html Rich Text Editor Renaldo enflaming his abetment begriming tonetically or bitterly after Iggy ingather and restyling spiritoso, platinic and Numidian. Rounding Roberto still stonker: obverse and terete Ave enforcing quite beamily but cauterizes her caruncle high. Wolf remains combatable after Granville yellows maritally or mends any dolefulness. The html elements to conceptualise something else can add to another source html rich and happy? This stuff with our text. Nvu when i commented the html code will toggle again. Will do it easy. In html generated by design and security stack web fonts, or edit it will close as expected editor based in html rich text editor allows users to control. Flexible image in html rich editor? Delightful and script files to vim is not be sure to get a good for wysiwyg text editor will be nested lists. The rich text editor font size can i like asking for editing for rich text editor automatically inserts the witcher the handler as java. Javascript libraries with html elements and html rich text editor that while we are you for modifying the optional subject to. Can see html rich text editor development plans you! There are planning to prevent your images can then click and is a table lists all. The rich text fields on different elements, but nowhere when you learn basic skills? Read italicized text editor plugin needs to rich text editor is not work on the skin apply styles, which is set a variety of the tool. Wysiwyg ux for the next list with this should learn new website that proper html tags, but that you need to implement the information security stack.
    [Show full text]
  • Integrating the World-Wide Web and Multi-User Domains to Support Advanced Network-Based Learning Environments
    Integrating The World-Wide Web and Multi-User Domains to Support Advanced Network-Based Learning Environments Lee A. Newberg, Richard O. Rouse III, and John A. Kruper Biological Sciences Division O±ce of Academic Computing The University of Chicago Chicago, Illinois, USA E-Mail: [email protected] October 21, 1994 The World-Wide Web consists of over ¯ve million documents distributed throughout the world and organized by a web of hypertext links connecting related topics. Object- Oriented Multi-User Domains are text- and network-based applications that allow in- dividuals to converse in real time with each other and to interact with user-de¯ned simulation objects. As part of our e®orts to develop advanced network-based learning tools, we describe how we have integrated these two highly powerful and popular Inter- net applications. Our integration merges the strengths of the World-Wide Web (font styles, images, hypermedia, and hypertext), with the strengths of Multi-User Domains (interactivity and easy construction of software controlled objects). 1 Introduction 1.1 The World-Wide Web The World-Wide Web consists of over ¯ve million documents and a vast collection of database information distributed throughout the world and organized by a web of hypertext links connecting related topics. Reflecting the popularity and growth of this distributed information system, Web-based information is doubling every six months to a year. Much of the power of the Web is derived from its seamlessness and ease of use. By clicking the mouse a user can fetch a page of information from any computer worldwide without knowing anything about how a given page is located, generated, or retrieved.
    [Show full text]
  • Plain Text by Brian Patterson
    from NOVEMBER 2014 Volume 26, Issue 4 A publication of the American Society of Trial Consultants FAVORITE THING Plain Text by Brian Patterson LAIN TEXT IS THE COCKROACH of file types: it will out- You can write in plain text without worrying about what it live us all. If you’ve ever tried opening a document from will eventually look like. It is sort of like writing in long hand, Pan old or obsolete word processor or page layout pro- except with a keyboard and screen instead of a pen and paper. gram, you know how difficult, if not impossible, it is to do. If The content is the center of attention, not which font to use, you can find software that will actually open it, you might be how big the font should be, how far apart the lines should be, lucky enough to see something you recognize hidden among or the millions of other choices a program like Microsoft Word the computer gibberish that surrounds it. Digging through the puts in front of us. rubble to salvage what you can may eventually get you some- thing useful, but it’s no one’s idea of a good time. Many things you write never have to go beyond plain, un- formatted text. Notes (maybe organized with a program such On the other hand, if you have any old .txt files you want to as Simplenote or Drafts) or todo lists may never leave their browse, they’ll open easily and look exactly the same as they did humble beginnings.
    [Show full text]