Practical R Exercises in swirl

Introduction to swirl, basic building blocks.

S.W.I.R.L or Statistics With Interactive R Learning was developed by a student at the John Hopkins department of biomechanics, Nick Carchedi.

Data Structure: any object that contains data. Numeric vectors are the simplest type of data structure in R. A number is considered a vector of length one.

c(), concatenate or combine , creates a vector. You can assign any number of operations to a vector and they will be applied iteratively to each element. If z <- c (1, 2, 3), z 2 + 100 is this: z c(2, 2, 2) + c(100, 100, 100). c(1, 2, 3, 4) + c(0, 10) is really c(1, 2, 3, 4) + c(0, 10, 0, 10) [1] 1 12 3 14 This is called vector recycling . When one vector does not divide by the other, R warns us.

? function-name brings out the guide on said function. If a função is a symbol you have to use backqoutes. --ex. ? : --

Workspace anf Files

getwd() finds working directory setwd sets working directory ls() lists current variables rm(list=ls()) clear variables list.files() or dir() lists all files in current directory file.create() creates a file file.exists() checks existence of file file.info() checks info on file You can use the $ operator --- e.g., file.info("mytest.R")$mode --- to grab specific items. file.rename renames files file.remove deletes files file.copy copies files file.path shows relative file path You can use file.path to construct file and directory paths that are independent of the operating system your R code is running on.

Create a directory in the current working directory called "testdir2" and a subdirectory for it called "testdir3", all in one command by using dir.create() and file.path().

dir.create(file.path("testdir2","testdir3"), recursive=TRUE )

Sequences and Numbers

number1:number2 is used to create a sequence of numbers from number1 to number2. Numbers are added on, one by one from number1 to number2 even is number1 is irrational. If number1 < number2 then the numbers go down increments of one.

seq(first, last, by=increment (or) length=size) does the same thing.

rep(a, b) repeats a, b times. "a" can be a vector sequence that is repeated rep(a, times=b) , or where each item in the vector is repeated b times rep(a, each=b) .

Atomic Vectors

  • TRUE (1), FALSE (0), NA (Not available)
  • They appear through logical conditions which use logical operators.
  • logical operators: >, <, <=, >=, ==, !=
  • A | B = A ou B; A&B = A e B; !A = não A
  • Multiplie data types

paste() collapses a sequence of characters in a vector. paste() prints and joins character vectors.

Always remeber the affects of vector recycling

Missing Values

NA are missing values. They will not suffer the effects of math operations.

NaN means not a number . IT is the result of operations such as deviding zero by zero (0/0) or subtracting infinity from infinity (Inf - Inf).

rnorm(h) draws h random numbers from a normal distribution sample(b, a) draws a random sample size a from data b is.na(f) returns TRUE if NA condition in relation to the collection f

Since TRUE are ones and FALSE are zeros, the sum shows TRUE's frequency.

Subsetting Vectors

Index vectors come in four flavours:

  • Logical Vectors
  • Vectors of Positive Integers
  • Vectors of Negative Integers
  • Vectors of Character Strings

x[1:10] brings about the first 10 elements in x for it brings up the numbers by the indices 1 through 10. R uses one-based indexing so indices start with 1. If you ask R something that is not in the boundaries of x, there will be no error. It will bring forth either NA or a numeric 0.

x[c(-2, -10)] brings us everything except element with index 2 and 10. Same with x[-c(2, 10)] and x[-2 & -10] etc.

x[is.na(x)] brings about a subset of all NAs in x

x[!is.na(x)] brings all the elements that are not NA in x

Logical operations bring out logical vectors. Placing logical vectors in keys after a avariable makes a selection in the variable to create a subset based on the logical operation inside the keys.

Named Elements

c(nome = element) create an element with name "nome".

names(x) finds names in vector.

names(x) <- places names in vectors.

identical() chehcks if two variables are the same

We can call on vectors by name --ex. x[c("bar", "foo")]--

Matrices and Data Frames

Matrices and Data frames represent rectangular data types: they store tabular data. Matrices contain only one class of data while Data Frames do not have that limit.

dim() brings up the dimension of th vector. We can also use it to apply a dimension. attributes() brings up vector attributes.

class() brings up class of variable

matrix() creates a matrix.

cbind() binds coloumn to matrix/data table

Coersion is when all elements in a vector transform into the same class. This happens when you try to place differently classed elements in a matrix, for example.

length() shows the length of the vector.

data.frame() creates a data frame.

colnames(x) <- creates coloumn names for the data table x.

results matching " "

No results matching " ".

What is swirl? Part 1

  • Swirl is an R package that turns the R console into an interactive learning evironment.
  • Students are guided through R programming exercises where they can answer questions in the R console.
  • There is no separation between where a student learns to use R, and where they go on to use R for thier own creative purposes.

If you've never used swirl before you shoud try swirl out for yourself:

What is swirl? Part 2

  • Anyone can create and distribute their own swirl course!
  • Creating a swirl course can allow you scale R and data science education within your company or school.
  • If you're interested in getting involved in the open source education community you can release your swirl course online and Team swirl will promote it for you!
  • There's a package called swirlify which is designed to help you write a swirl course. We'll look into swirlify later.

What is a swirl course?

  • A swirl course is a directory that contains all of the files, folders, and lessons associated with the course you are developing.
  • Lessons contain most of the content that students interact with, and the course sequentially organizes these lessons.
  • A course should conceptually encapsulate a broad concept that you want to teach. For example: “Plotting in R” or “Statistics for Engineers” are broad enough topics that they could be broken down further (into lessons which we’ll talk about next).
  • When a student start swirl, they will prompted to choose from a list of courses, and then they can choose a lesson within the course they selected.
  • Once the student selects a lesson, swirl will start asking the student questions in the R console.

What is a lesson?

  • A lesson is a directory that contains all of the files required to execute one unit of instruction inside of swirl.
  • For example a "Plotting in R" course might contain the lessons: "Plotting with Base Graphics", "Plotting with Lattice", and "Plotting with ggplot2."
  • Every lesson must contain one lesson.yaml file which structures the text that the student will see inside the R console while they are using swirl.
  • The lesson.yaml file contains a sequence of questions that students will be prompted with.

Writing swirl Courses: Setting up the App

First install swirlify:

Then set your working directory to wherever you want to create your course and start the Shiny lesson authoring app:

Writing swirl Courses: Using the App

For a demo about how to use the Shiny authoring app see the following video: https://youtu.be/UPL_W-Umgjs

Writing swirl Courses: Using the R Console

  • Alternatively you can use the R console and a text editor to write swirl lessons.
  • We highly recommend using RStudio for writing swirl lessons since RStudio provides this editor and console setup by default.

To start a new lesson from the R console set your working directory to where you want to create the course, and then use the new_lesson() function to create the course:

Writing Lessons: Part 1

The new_lesson() function will create a file and folder structure like this in your working directory:

Writing Lessons: Part 2

To review, the new_lesson() function did the following:

  • A new directory was created in /Users/sean/ called My_New_Course .
  • A new directory was created in /Users/sean/My_New_Course called My_First_Lesson .

Writing Lessons: Part 2.5

  • lesson.yaml is where you will write all of the questions for this lesson. ( Example )
  • initLesson.R is an R script that is run before the lesson starts which is usually used to load data or set up environmental variables. ( Example )
  • dependson.txt is the list of R packages your lesson will require. swirl will install these packages if the user doesn't already have them installed. ( Example )
  • customTests.R is where you can write your own tests for student's answers. ( Example )

Writing Lessons: Part 3

If everything is set up correctly then new_lesson() should have opened up the new lesson.yaml file in a text editor. You can now start adding questions to the lesson.yaml by using functions that start with wq_ (write question).

Writing Lessons: Types of Questions

Lessons are sequences of questions that have the following general structure:

The example above shows the high-level structure for two questions.

  • Each question is demarcated with a hyphen.
  • Every question starts with a Class that specifies that question's behavior inside of swirl.
  • What follows the class is a set of key-value pairs that will be used to render the question when a student is using swirl.

Writing Lessons: The Meta Question

The first question in every lesson.yaml is always the meta question which contains general information about the course. Below is an example of the meta question:

The meta question will not be displayed to a student. The only fields you should modify are Author and Organization fields.

Writing Lessons: Message Questions

Message questions display a string of text in the R console for the student to read. Once the student presses enter, swirl will move on to the next question.

Add a message question using wq_message() .

Here's an example message question:

The student will see the following in the R console:

Writing Lessons: Command Questions

Command questions prompt the student to type an expression into the R console.

  • The CorrectAnswer is entered into the console if the student uses the skip() function.
  • The Hint is displayed to the student if they don't get the question right.
  • The AnswerTests determine whether or not the student answered the question correctly. See the answer testing section for more information.

Add a message question using wq_command() .

Here's an example command question:

Multiple Choice Questions

Multiple choice questions present a selection of options to the student. These options are presented in a different order every time the question is seen.

  • The AnswerChoices should be a semicolon separated string of choices that the student will have to choose from.

Add a message question using wq_multiple() .

Here's an example multiple choice question:

Other Question Types

For complete documentation about writing swirl courses and lessons see the swirlify website: http://swirlstats.com/swirlify/

Organizing Lessons: Part 1

Let's revisit the general structure of a swirl course. This is the structure of a course with two lessons:

Organizing Lessons: Part 2

  • By default each folder in My_New_Course will be displayed to the student as a lesson they can select.
  • If you want to explicitly specify the order in which lessons are displayed you will need to add a MANIFEST file to your course.
  • You can do this with the add_to_manifest() function, which will add the lesson you are currently working on to the MANIFEST . You can also edit the MANIFEST yourself in a text editor.

Organizing Lessons: Part 3

The (abridged) MANIFEST file below belongs to Team swirl's R Programming course:

Sharing Your Course

Swirlify makes sharing a swirl course easy. We recommend three different methods for sharing a swirl course.

Sharing Your Course as a File

We've developed the .swc file type so that you can share your course as a single file. Creating an .swc file for your course is easy:

  • Set any lesson in the course you want to share as the current lesson using set_lesson() .
  • Create an .swc file using the pack_course() function. Your .swc file will appear in the same directory as the directory that contains the course folder. You also have the option to export the .swc file to another directory by specifying the export_path argument.
  • You can now share your .swc file like you would any other file (through email, file sharing services, etc).
  • Students can install your course from the .swc file by downloading the file and then using the install_course() function in swirl, which will prompt them to interactively select the file they downloaded.

Sharing Your Course on GitHub

  • We highly encourage you to develop your course on GitHub so that we can better support you if you have questions or need assistance while developing your course.
  • Developing your course on GitHub provides the added benefit that your course will be instantly ready to distribute.
  • Students can install your course from swirl using the install_course_github() function.
  • Make sure that your course directory is the root folder of your git repository. For examples of courses that have been shared on GitHub you can browse some of the courses on the Swirl Course Network .

Sharing Your Course on The Swirl Course Network

The goal of the Swirl Course Network is to list and organize all publicly available swirl courses. Visit the homepage of the SCN for more information.

After adding your course to the SCN students will be able to install your course using install_course("[Name of Your Course]") in swirl.

In order to add your course to the SCN:

  • Create an .swc file for your course.
  • Fork https://github.com/swirldev/scn on GitHub.
  • Add the .swc file to your fork.
  • Add an Rmd file to your fork like this one . You can include a description of your course, authors, a course website, and how to install your course.
  • Run rmarkdown::render_site() when your current directory is set to your fork.
  • Add, commit, and push your changes to GitHub, then send us a Pull Request.

More Help & Resources

  • The swirl Website
  • The swirlify Documentation
  • The swirl Course Network

Feel free to get in touch with Team swirl:

Get R Done! A travelers guide to the world of R

Chapter 8 swirl.

swirl is a system for running tutorials within the R console. R basically asks you questions and you type the answer. Information about downloading and using swirl can be found here: https://swirlstats.com/students.html

8.1 swirl quickstart:

In the R console run these commands:

To set everything up:

To get started type:

Swirl will guide you through the reset. Choose one of the R Programming tutorials.

A cheatsheet to swirl commands and other info can be found here: https://docs.google.com/presentation/d/12cNq9VYEUFzzzQkNmRF2PgllW05-tVqoEux26jfygWw/edit?usp=sharing

8.2 Installing Packages in RStudio & RStudio Cloud

R has many packages (aka “libraries”) that extend its functionality. Installing these can be a bit confusing. Watch this video for a brief overview. If you need more information there are other videos on YouTube.

Note: I go through this in RStudio Cloud, but it works the same way in regular RStudio.

https://youtu.be/UaS1OVb89S8

8.3 Getting to know swirl video

In this video I explain exactly what’s going on each step of the way as I work through a swirl tutorial (“Basic building blocks”). If what was happening during the swirl tutorial itself made sense then you probably don’t need to watch the video. If you were confused, watch this to see if it helps, pausing as needed to work on the tutorial.

The key vocabulary, concepts and functions covered in this tutorial are: * programming language * variable * + , - , / , and ^ * sqrt() * abs() * assignment operator * <- * help files * vector * c() function (“concatenate”, “combine”) * element wise operation (“element-by-element”) * recycling * vectorized operations (not discussed in those terms) * up arrow to view command history * tab completion (“auto-completion”)

8.4 A worked example of swirl “Sequences of Numbers”

In this video I explain exactly what’s going on each step of the way as I work through a swirl tutorial. If what was happening during the swirl tutorial itself made sense then you probably don’t need to watch the video. If you were confused, watch this to see if it helps, pausing as needed to work on the tutorial.

https://youtu.be/I6aoCVoKTm8

Arcus Education Portal

Data Education for the CHOP Researcher

Swirl: Learn R in R

If you haven’t had a chance to learn anything at all about R and want to, you have a couple of options. You could stop in at the R Lab for Beginners in which Joy Payton walks you through basic R functionality, or if you are a do-it-yourselfer, start here and discover the swirl package.

  • Windows users
  • Linux users
  • Updated Windows users
  • Updated Mac users
  • Updated Linux users

Open RStudio.

Find the console on RStudio. It’s one of the tabs. You should be able to put your cursor to the right of a “>” character. Do so.

Type these three lines, one by one. Give each command time to execute before executing the next one: if you try to execute them all at the same time, they may trip each other up. You may be prompted to allow installation of dependent packages. If so, acquiesce.

> install.packages("swirl") > library(swirl) > swirl()

After that, select the lesson you want to learn. If you have never done anything in R, you might want to start with the first lesson in the list.

Should you need them, here are some step-by-step videos to help you through the first few lessons in the Basic R course. They are meant to help you if you are stuck by providing answers and the rationales behind them:

  • Lesson 1: Basic Building Blocks
  • Lesson 2: Workspace and Files
  • Lesson 3: Sequences of Number s
  • Lesson 4: Vectors
  • Lesson 5: Missing Values
  • Lesson 6: Subsetting Vectors
  • Lesson 7: Matrices and Data Frames
  • Lesson 8: Logic
  • Lesson 9: Functions
  • Lesson 10: lapply and sapply
  • Lesson 11 (Coming soon)
  • Lesson 12 (Coming soon)
  • Lesson 13 (Coming soon)
  • Lesson 14 (Coming soon)
  • Lesson 15: Base Graphics

Like this article? Click "Like" to let us know. Like

Introduction to R and Rstudio

Chapter 4 basic building blocks.

This lesson deals with some basic building blocks of working with code in R.

In its simplest form, R can be used as an interactive calculator. Type 5 + 7 and press Enter.

R simply prints the result of 12 by default. However, R is a programming language and often the reason we use a programming language as opposed to a calculator is to automate some process or avoid unnecessary repetition.

In this case, we may want to use our result from above in a second calculation. Instead of retyping 5 + 7 every time we need it, we can just create a new variable that stores the result.

The way you assign a value to a variable in R is by using an assignment operator, which is just a ‘less than’ symbol followed by a ‘minus’ sign. It looks like this: <-

Think of the assignment operator as an arrow. You are assigning the value on the right side of the arrow to the variable name on the left side of the arrow.

To assign the result of 5 + 7 to a new variable called x, you type x <- 5 + 7 . This can be read as ‘object x will be assigned the value 5 plus 7’. Give it a try now.

You’ll notice that R did not print the result of 12 this time. When you use the assignment operator, R assumes that you don’t want to see the result immediately, but rather that you intend to use the result for something else later on.

Note that also the = sign is an assignment operator, so in R you also can use x = 5 + 7 . However, the automation in these exercises require you to use the operator <- instead of the operator = .

To view the contents of the variable x, just type x and press Enter. Try it now.

Now, store the result of x - 3 in a new variable called y.

What is the value of y? Type y to find out.

Now, let’s create a small collection of numbers called a vector. Any object that contains data is called a data structure and numeric vectors are the simplest type of data structure in R. In fact, even a single number is considered a vector of length one.

The easiest way to create a vector is with the c() function, which stands for ‘concatenate’ or ‘combine’. To create a vector containing the numbers 1.1, 9, and 3.14, type c(1.1, 9, 3.14). Try it now and store the result in a variable called z.

Anytime you have questions about a particular function, you can access R’s built-in help files via the ? command. For example, if you want more information on the c() function, type ?c without the parentheses that normally follow a function name. Give it a try.

Type z to view its contents. Notice that there are no commas separating the values in the output.

You can combine vectors to make a new vector. Create a new vector that contains z, 555, then z again in that order. Don’t assign this vector to a new variable, so that we can just see the result immediately.

Numeric vectors can be used in arithmetic expressions. Type the following to see what happens: z * 2 + 100.

First, R multiplied each of the three elements in z by 2. Then it added 100 to each element to get the result you see above.

Other common arithmetic operators are + , - , / , and ^ (where x^2 means ‘x squared’). To take the square root, use the sqrt() function and to take the absolute value, use the abs() function.

Take the square root of z - 1 and assign it to a new variable called my_sqrt.

Before we view the contents of the my_sqrt variable, what do you think it contains?

a vector of length 3

  • a single number (i.e a vector of length 1)
  • a vector of length 0 (i.e. an empty vector)

Print the contents of my_sqrt.

As you may have guessed, R first subtracted 1 from each element of z, then took the square root of each element. This leaves you with a vector of the same length as the original vector z.

Now, create a new variable called my_div that gets the value of z divided by my_sqrt.

Which statement do you think is true?

The first element of my_div is equal to the first element of z divided by the first element of my_sqrt, and so on…

  • my_div is a single number (i.e a vector of length 1)
  • my_div is undefined

Go ahead and print the contents of my_div.

When given two vectors of the same length, R simply performs the specified arithmetic operation ( + , - , * , etc.) element-by-element. If the vectors are of different lengths, R ‘recycles’ the shorter vector until it is the same length as the longer vector.

When we did z * 2 + 100 in our earlier example, z was a vector of length 3, but technically 2 and 100 are each vectors of length 1.

Behind the scenes, R is ‘recycling’ the 2 to make a vector of 2s and the 100 to make a vector of 100s. In other words, when you ask R to compute z * 2 + 100, what it really computes is this: z * c(2, 2, 2) + c(100, 100, 100).

To see another example of how this vector ‘recycling’ works, try adding c(1, 2, 3, 4) and c(0, 10). Don’t worry about saving the result in a new variable.

If the length of the shorter vector does not divide evenly into the length of the longer vector, R will still apply the ‘recycling’ method, but will throw a warning to let you know something fishy might be going on.

Try c(1, 2, 3, 4) + c(0, 10, 100) for an example.

Before concluding this lesson, I’d like to show you a couple of time-saving tricks.

Earlier in the lesson, you computed z * 2 + 100. Let’s pretend that you made a mistake and that you meant to add 1000 instead of 100. You could either re-type the expression, or…

In many programming environments, the up arrow will cycle through previous commands. Try hitting the up arrow on your keyboard until you get to this command (z * 2 + 100), then change 100 to 1000 and hit Enter. If the up arrow doesn’t work for you, just type the corrected command.

Finally, let’s pretend you’d like to view the contents of a variable that you created earlier, but you can’t seem to remember if you named it my_div or myDiv. You could try both and see what works, or…

You can type the first two letters of the variable name, then hit the Tab key (possibly more than once). Most programming environments will provide a list of variables that you’ve created that begin with ‘my’. This is called auto-completion and can be quite handy when you have many variables in your workspace. Give it a try. (If auto-completion doesn’t work for you, just type my_div and press Enter.)

You’ve successfully completed this lesson!

  • Best Practice
  • 1: Getting Started
  • 2: Working with Data
  • 3: Grouped Data
  • 4: Continuous Data
  • 5: Graphics
  • 6: Programming

Introduction to SWIRL

What is swirl.

Statistics With Interactive R Learning

Every new tech thing needs a nice acronym and logo

What SWIRL is

an R package for teaching and learning statistics and R simultaneously and interactively

Lessons are a dialogue between swirl and the user

Composed of:

  • text output,
  • multiple choice and text-based questions,
  • and (most importantly) questions that require the user to enter actual R code at the prompt.

Responses are evaluated for correctness based on instructor-specified answer tests.

  • Appropriate feedback is given immediately to the user.

Why are we using swirl?

Students work directly in R console = real working environment

Allows immediate evaluation of code and immediate feedback

Allows remote logging of scores so I can check progress

How to use SWIRL

1. install swirl package.

You only need to do this once.

2. Install the lessons

Lessons are on the intro2r GitHub page

(github = social coding site, sharing code)

You only need to do this once for each Unit (unless we update the lessons … ).

This command downloads the first set of lessons to your computer.

3. Start swirl

You will need to do this every time you start R or want to continue an old lesson or start a new lesson.

4. Choose a name

Enter your name.

I will need to be able to identify you, so please use:

  • firstname lastname, or

This name will also allow you to continue lessons if you stop them in the middle.

5. Choose a course

Enter the number of the course you want to work on.

6. Choose a lesson

Choose the first lesson: Basic Building Blocks

7. Do the lesson!

Hit ‘Enter’ to advance when presented with ‘…’

The screen also shows you how far through the lesson you are (0%).

8. Completing the lesson

You will need to be connected to the internet to submit your lesson

When you are done, the last question will ask if you want to submit your answers to me to verify that your completed the lesson.

You should enter the number of your response (usually ‘1’).

This will bring up a new web page, a Google form.

Scroll down, and click ‘submit’.

This will send an encrypted response to the Google form so that we can verify you completed the lesson.

Some useful commands for swirl

Leave swirl temporarily and gain access to the console again

Return to swirl after playing

Return to the main menu

Display a list of these special commands

Intro R with swirl

practice programming assignment swirl lesson 2 workspace and files

Chapter 3 R Programming with swirl

This exercise will have you utilize an R tutorial package called swirl , which will allow you to learn R from within R. Using swirl , you will complete a series of lessons that will teach you the fundamentals of R programming.

3.1 Complete your first swirl lesson

Estimated time: 20 min

Open RStudio.

In the R console window, type the following commands to load the swirl package:

Install the course “ R Programming: The basics of programming in R ”, by following the instructions provided by swirl.

  • Enter your name.
  • Press ENTER .
  • Enter 1 , 2 , or 3 .
  • Install the course “R Programming: The basics of programming in R”.

Complete your first lesson.

  • Select “ R Programming ”.
  • Select “ Basic Building Blocks ”, by entering 1 ( i.e. the corresponding lesson number ).
  • Follow the instructions provided by swirl to complete your first lesson.
  • At the end, when swirl asks if you would like to receive Coursera credit, select “No”.

3.2 Complete additional swirl lessons

Estimated time: 80 min

  • Select “ R Programming ”
  • 5: Missing_Values
  • 6: Subsetting_Vectors
  • 12: Looking_at_Data
  • To exit swirl, type bye() in the R console, press ESC on your keyboard, or enter 0 in response to the swirl course menu prompt.

Instantly share code, notes, and snippets.

@sibyvt

sibyvt / Assignment: swirl Lesson 1: Basic Building Blocks

  • Download ZIP
  • Star 4 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • Save sibyvt/9c9ea23550f5037d5cff98456fa75503 to your computer and use it in GitHub Desktop.

@mariaoduwaiye

mariaoduwaiye commented Dec 31, 2018

Sorry, something went wrong.

@Lerato93

Lerato93 commented Aug 4, 2020

Very helpful, thank you

@LeonByer

LeonByer commented Dec 10, 2020

What a voluminous code. How much effort has gone into displaying it all for educational purposes.

@mswest1

mswest1 commented Jul 10, 2021

Very helpful for me learning R basics!!! :)

@Robert2Connolly

Robert2Connolly commented Jul 13, 2022

Thanks for the tip, I will definitely use it. Right now I'm working on a project for service https://essays.edubirdie.com/research-proposal-writing-service with research proposal writing for students. That way we are trying to help with training so that students can learn more quickly and have the opportunity to start working on their careers while they are still at university.

@Parimahajializadeh

Parimahajializadeh commented Jul 22, 2022

@Aus-tin

Aus-tin commented Mar 27, 2023

very helpful, thank you so much

social collaboration and other worthwhile dilemmas

Swirl – R porgramming – Lesson 7 – Matrices and Data Frames

| Please choose a course, or type 0 to exit swirl.

1: R Programming 2: Take me to the swirl course repository!

Selection: 1

| Please choose a lesson, or type 0 to return to course menu.

1: Basic Building Blocks 2: Workspace and Files 3: Sequences of Numbers 4: Vectors 5: Missing Values 6: Subsetting Vectors 7: Matrices and Data Frames 8: Logic 9: Functions 10: lapply and sapply 11: vapply and tapply 12: Looking at Data 13: Simulation 14: Dates and Times 15: Base Graphics

Selection: 7 | | 0%

| In this lesson, we’ll cover matrices and data frames. Both represent ‘rectangular’ data types, meaning that | they are used to store tabular data, with rows and columns.

… |=== | 3% | The main difference, as you’ll see, is that matrices can only contain a single class of data, while data | frames can consist of many different classes of data.

… |====== | 6% | Let’s create a vector containing the numbers 1 through 20 using the `:` operator. Store the result in a | variable called my_vector.

> my_vector my_vector(1:20) Error: could not find function “my_vector” > my_vector my_vector [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

| Excellent work! |=========== | 11% | The dim() function tells us the ‘dimensions’ of an object. What happens if we do dim(my_vector)? Give it a | try.

> dim(my_vector) NULL

| You nailed it! Good job! |============== | 14% | Clearly, that’s not very helpful! Since my_vector is a vector, it doesn’t have a `dim` attribute (so it’s just | NULL), but we can find its length using the length() function. Try that now.

> length(my_vector) [1] 20

| All that hard work is paying off! |================= | 17% | Ah! That’s what we wanted. But, what happens if we give my_vector a `dim` attribute? Let’s give it a try. Type | dim(my_vector) dim(my_vector) dim(my_vector) [1] 4 5

| All that hard work is paying off! |========================== | 25% | Another way to see this is by calling the attributes() function on my_vector. Try it now.

> attributes(my_vector) $dim [1] 4 5

| That’s correct! |============================= | 28% | Just like in math class, when dealing with a 2-dimensional object (think rectangular table), the first number | is the number of rows and the second is the number of columns. Therefore, we just gave my_vector 4 rows and 5 | columns.

… |=============================== | 31% | But, wait! That doesn’t sound like a vector any more. Well, it’s not. Now it’s a matrix. View the contents of | my_vector now to see what it looks like.

> my_vector [,1] [,2] [,3] [,4] [,5] [1,] 1 5 9 13 17 [2,] 2 6 10 14 18 [3,] 3 7 11 15 19 [4,] 4 8 12 16 20

| All that practice is paying off! |================================== | 33% | Now, let’s confirm it’s actually a matrix by using the class() function. Type class(my_vector) to see what I | mean.

> class(my_vector) [1] “matrix”

| Your dedication is inspiring! |===================================== | 36% | Sure enough, my_vector is now a matrix. We should store it in a new variable that helps us remember what it | is. Store the value of my_vector in a new variable called my_matrix.

> my_matrix ?matric() Error in .helpForCall(topicExpr, parent.frame()) : no methods for ‘matric’ and no documentation for it as a function > ?matrix() starting httpd help server … done

| Almost! Try again. Or, type info() for more options.

| The command ?matrix will do the trick.

| That’s a job well done! |============================================== | 44% | Now, look at the documentation for the matrix function and see if you can figure out how to create a matrix | containing the same numbers (1-20) and dimensions (4 rows, 5 columns) by calling the matrix() function. Store | the result in a variable called my_matrix2.

> my_matrix2 identical(my_matrix, mymatrix2) Error in identical(my_matrix, mymatrix2) : object ‘mymatrix2’ not found > identical(my_matrix, my_matrix2) [1] TRUE

| Keep working like that and you’ll get there! |==================================================== | 50% | Now, imagine that the numbers in our table represent some measurements from a clinical experiment, where each | row represents one patient and each column represents one variable for which measurements were taken.

… |====================================================== | 53% | We may want to label the rows, so that we know which numbers belong to each patient in the experiment. One way | to do this is to add a column to the matrix, which contains the names of all four people.

… |========================================================= | 56% | Let’s start by creating a character vector containing the names of our patients — Bill, Gina, Kelly, and | Sean. Remember that double quotes tell R that something is a character string. Store the result in a variable | called patients.

> patients cbind(pateints, my_matrix) Error in cbind(pateints, my_matrix) : object ‘pateints’ not found > cbind(patients, my_matrix) patients [1,] “Bill” “1” “5” “9” “13” “17” [2,] “Gina” “2” “6” “10” “14” “18” [3,] “Kelly” “3” “7” “11” “15” “19” [4,] “Sean” “4” “8” “12” “16” “20”

| All that practice is paying off! |=============================================================== | 61% | Something is fishy about our result! It appears that combining the character vector with our matrix of numbers | caused everything to be enclosed in double quotes. This means we’re left with a matrix of character strings, | which is no good.

… |================================================================== | 64% | If you remember back to the beginning of this lesson, I told you that matrices can only contain ONE class of | data. Therefore, when we tried to combine a character vector with a numeric matrix, R was forced to ‘coerce’ | the numbers to characters, hence the double quotes.

… |===================================================================== | 67% | This is called ‘implicit coercion’, because we didn’t ask for it. It just happened. But why didn’t R just | convert the names of our patients to numbers? I’ll let you ponder that question on your own.

… |======================================================================== | 69% | So, we’re still left with the question of how to include the names of our patients in the table without | destroying the integrity of our numeric data. Try the following — my_data my_data my_data patients X1 X2 X3 X4 X5 1 Bill 1 5 9 13 17 2 Gina 2 6 10 14 18 3 Kelly 3 7 11 15 19 4 Sean 4 8 12 16 20

| Your dedication is inspiring! |============================================================================= | 75% | It looks like the data.frame() function allowed us to store our character vector of names right alongside our | matrix of numbers. That’s exactly what we were hoping for!

… |================================================================================ | 78% | Behind the scenes, the data.frame() function takes any number of arguments and returns a single object of | class `data.frame` that is composed of the original objects.

… |=================================================================================== | 81% | Let’s confirm this by calling the class() function on our newly created data frame.

> class(my_data) [1] “data.frame”

| You are amazing! |====================================================================================== | 83% | It’s also possible to assign names to the individual rows and columns of a data frame, which presents another | possible way of determining which row of values in our table belongs to each patient.

… |========================================================================================= | 86% | However, since we’ve already solved that problem, let’s solve a different problem by assigning names to the | columns of our data frame so that we know what type of measurement each column represents.

… |============================================================================================ | 89% | Since we have six columns (including patient names), we’ll need to first create a vector containing one | element for each column. Create a character vector called cnames that contains the following values (in order) | — “patient”, “age”, “weight”, “bp”, “rating”, “test”.

> names cnames colnames(my_data) [1] “patients” “X1” “X2” “X3” “X4” “X5”

| You almost had it, but not quite. Try again. Or, type info() for more options.

| Try colnames(my_data) colnames(my_data) my_data patient age weight bp rating test 1 Bill 1 5 9 13 17 2 Gina 2 6 10 14 18 3 Kelly 3 7 11 15 19 4 Sean 4 8 12 16 20

| That’s correct! |==================================================================================================== | 97% | In this lesson, you learned the basics of working with two very important and common data structures — | matrices and data frames. There’s much more to learn and we’ll be covering more advanced topics, particularly | with respect to data frames, in future lessons.

… |=======================================================================================================| 100% | Would you like to receive credit for completing this course on Coursera.org?

1: Yes 2: No

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Twitter (Opens in new window)

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

  • Swirl Data Wrangling Lesson 1: "Manipulating Data with dplyr"
  • by Nunno Nugroho
  • Last updated almost 6 years ago
  • Hide Comments (–) Share Hide Toolbars

Twitter Facebook Google+

Or copy & paste this link into an email or IM:

swirl – R Programming – Lesson 15 – Base Graphics

Share this:, 2 thoughts on “swirl – r programming – lesson 15 – base graphics”.

I am getting an error when I pass the argument for the graph:

plot(x = cars$speed, y = cars$dist) Error in plot.window(…) : need finite ‘xlim’ values In addition: Warning messages: 1: In min(x) : no non-missing arguments to min; returning Inf 2: In max(x) : no non-missing arguments to max; returning -Inf 3: In min(x) : no non-missing arguments to min; returning Inf 4: In max(x) : no non-missing arguments to max; returning -Inf

plot(x = cars$speed, y = cars$dist)

Comments are closed.

A Scientific Programming Sketchbook

IMAGES

  1. lesson 2 Workspace and Files, permission denied for dir.create · Issue

    practice programming assignment swirl lesson 2 workspace and files

  2. SWIRL

    practice programming assignment swirl lesson 2 workspace and files

  3. 2. R Programming 기초배우기- Swirl 설치하기

    practice programming assignment swirl lesson 2 workspace and files

  4. Assignment 2

    practice programming assignment swirl lesson 2 workspace and files

  5. The Easiest way to Learn R Programming

    practice programming assignment swirl lesson 2 workspace and files

  6. Assignment 1.docx

    practice programming assignment swirl lesson 2 workspace and files

VIDEO

  1. Code.org Lesson 1.1 Variables

  2. How to Practice and Improve Your Programming Skills

  3. CP Soap Swirls with two colors

  4. NPTEL The Joy of Computing using Python week 2 quiz assignment answers with proof of each answer

  5. Programming, Data Structures and Algorithms using Python || NPTEL week 2 answers 2023 || #nptel

  6. Activity 2.2.3 Server Analysis

COMMENTS

  1. swirl

    2: Take me to the swirl course repository! Selection: 1. | Please choose a lesson, or type 0 to return to course menu. 1: Basic Building Blocks 2: Workspace and Files. 3: Sequences of Numbers 4: Vectors. 5: Missing Values 6: Subsetting Vectors. 7: Matrices and Data Frames 8: Logic.

  2. SWIRL

    Practice Programming Assignment: swirl Lesson 2: Workspace and Files Selection: 2 | | 0% | In this lesson, you'll learn how to examine your local workspace in R and begin to | explore the relationship between your workspace and the file system of your machine. |== | 2% | Because different operating systems have different conventions with regards to things like file paths, the outputs | of ...

  3. S SB Workshop 1 R Programming 2 Workspace and Files

    https://github.com/telescopeuser/S-SB-Workshophttps://youtu.be/jfn8mtn9tEo

  4. Practical R Exercises in swirl · GitBook

    Practical R Exercises in swirl Introduction to Swirl Basic Building Blocks. S.W.I.R.L or Statistics With Interactive R Learning was developed by a student at the John Hopkins department of biomechanics, Nick Carchedi.. Data Structure: any object that contains data. Numeric vectors are the simplest type of data structure in R.

  5. GitHub

    R Programming: The basics of programming in R; R Programming E: Same as the original, but modified slightly for in-class use (see below ***); The R Programming Environment *** R Programming E is identical to R Programming, except we've eliminated the prompts for Coursera credentials at the end of each lesson and instead give students the option to send an email to their instructor notifying ...

  6. Chapter 9 A guide to current swirl tutorials

    27.7.2 The assignment operator "<-" 27.8 Optional: Plot the Mendley 1998 data; 27.9 Loading .csv files using RStudio [ ] 27.10 Challenge; 28 Interactive resources for learning R. 28.1 RStudio Cloud Primers (FREE! Total beginners). 28.2 swirl Interactive Primers. 28.2.1 swirl quickstart: 29 R Learning Books. 29.1 Learning R for Bioinformatics

  7. R Programming

    Week 1 Quiz • 30 minutes. 7 programming assignments • Total 1,260 minutes. swirl Lesson 1: Basic Building Blocks • 180 minutes. swirl Lesson 2: Workspace and Files • 180 minutes. swirl Lesson 3: Sequences of Numbers • 180 minutes. swirl Lesson 4: Vectors • 180 minutes. swirl Lesson 5: Missing Values • 180 minutes.

  8. swirl

    The (abridged) MANIFEST file below belongs to Team swirl's R Programming course: Basic_Building_Blocks Workspace_and_Files Sequences_of_Numbers Vectors Missing_Values Subsetting_Vectors Matrices_and_Data_Frames Sharing Your Course. Swirlify makes sharing a swirl course easy. We recommend three different methods for sharing a swirl course.

  9. Chapter 8 swirl

    27.7.2 The assignment operator "<-" 27.8 Optional: Plot the Mendley 1998 data; 27.9 Loading .csv files using RStudio [ ] 27.10 Challenge; 28 Interactive resources for learning R. 28.1 RStudio Cloud Primers (FREE! Total beginners). 28.2 swirl Interactive Primers. 28.2.1 swirl quickstart: 29 R Learning Books. 29.1 Learning R for Bioinformatics

  10. Swirl: Learn R in R

    Open RStudio. Find the console on RStudio. It's one of the tabs. You should be able to put your cursor to the right of a ">" character. Do so. Type these three lines, one by one. Give each command time to execute before executing the next one: if you try to execute them all at the same time, they may trip each other up.

  11. Chapter 4 Basic Building Blocks

    Chapter 4. Basic Building Blocks. This lesson deals with some basic building blocks of working with code in R. In its simplest form, R can be used as an interactive calculator. Type 5 + 7 and press Enter. 5 + 7 ## [1] 12. R simply prints the result of 12 by default. However, R is a programming language and often the reason we use a programming ...

  12. GitHub: Let's build from here · GitHub

    {"payload":{"allShortcutsEnabled":false,"fileTree":{"":{"items":[{"name":"Assignment_ swirl Lesson 1_ Basic Building Blocks.txt","path":"Assignment_ swirl Lesson 1 ...

  13. Introduction to SWIRL

    This will send an encrypted response to the Google form so that we can verify you completed the lesson. Some useful commands for swirl bye() Exit swirl. play() Leave swirl temporarily and gain access to the console again. nxt() Return to swirl after playing. main() Return to the main menu. info() Display a list of these special commands

  14. RPubs

    Swirl Data Wrangling Lesson 2: "Grouping and Chaining with dplyr" by Nunno Nugroho; Last updated almost 6 years ago Hide Comments (-) Share Hide Toolbars

  15. Chapter 3 R Programming with swirl

    swirl() Install the course " R Programming: The basics of programming in R ", by following the instructions provided by swirl. Enter your name. Press ENTER. Enter 1, 2, or 3. Install the course "R Programming: The basics of programming in R". Complete your first lesson. Select " R Programming ". Select " Basic Building Blocks ...

  16. Assignment: swirl Lesson 1: Basic Building Blocks · GitHub

    To take the square root, use the sqrt () function and to take. | the absolute value, use the abs () function. ... | Take the square root of z - 1 and assign it to a new variable called my_sqrt. | Keep trying! Or, type info () for more options. | Assign the result of sqrt (z - 1) to a variable called my_sqrt.

  17. swirl

    Previous Post swirl - R Programming - Lesson 8 - Logic Next Post swirl - R Programming - Lesson 10 ... To get through the Swirl lesson, submit the function and invoke it like this at the console (type the following and hit enter): ... Step 2: create a new file and save it (e.g. test.R)

  18. Swirl

    Selection: 1. | Please choose a lesson, or type 0 to return to course menu. 1: Basic Building Blocks 2: Workspace and Files 3: Sequences of Numbers. 4: Vectors 5: Missing Values 6: Subsetting Vectors. 7: Matrices and Data Frames 8: Logic 9: Functions. 10: lapply and sapply 11: vapply and tapply 12: Looking at Data.

  19. swirl

    2: Take me to the swirl course repository! Selection: 1. | Please choose a lesson, or type 0 to return to course menu. 1: Basic Building Blocks 2: Workspace and Files. 3: Sequences of Numbers 4: Vectors. 5: Missing Values 6: Subsetting Vectors. 7: Matrices and Data Frames 8: Logic.

  20. RPubs

    Swirl Data Wrangling Lesson 1: "Manipulating Data with dplyr" by Nunno Nugroho; Last updated almost 6 years ago Hide Comments (-) Share Hide Toolbars

  21. swirl

    Previous Post swirl - R Programming - Lesson 12 - Looking At Data Next Post swirl - R Programming Lesson 14 - Dates and Times. One thought on "swirl - R Programming - Lesson 13 - Simulation" ... Good Practice (1) Hackathon (2) HPC (1) Intel Edison (2) IPython (1) JavaScript (9) kaggle (1) Mac (2) Machine Learning (7) Maths ...

  22. swirl

    Previous Post swirl - R Programming Lesson 14 - Dates and Times Next Post Setup MarkdownEditing Plugin for Sublime Text Editor. 2 thoughts on "swirl - R Programming - Lesson 15 - Base Graphics" ... Good Practice (1) Hackathon (2) HPC (1) Intel Edison (2) IPython (1) JavaScript (9) kaggle (1) Mac (2) Machine Learning (7) Maths (8 ...