r-homework1.R
to yourlastname_sudentID_r-homework1.R
(save as in RStudio)Start by making a vector named ‘myvector’ with the numbers 1 through 26. Create another vector named, ‘myvectimestwo’ by multiply the vector by 2, and give the resulting vector names A through Z (hint: there is a built in vector called LETTERS
)
matrix
!)You can create a new data frame right from within R with the following syntax:
df <- data.frame(id = c('a', 'b', 'c'),
x = 1:3,
y = c(TRUE, TRUE, FALSE),
stringsAsFactors = FALSE)
Make a data frame that holds the following information for yourself:
Column names should be first_name, last_name, & lucky_number Then use rbind
to add an entry for someone else in the class or someone you know. Finally, use cbind
to add a column named ‘coffee’ with each person’s answer to the question, “Is it time for coffee break?”
Given the following list:
xlist <- list(a = "Software Carpentry", b = 1:10, data = head(iris))
Using your knowledge of both list and vector subsetting, extract the number 2 from xlist. Hint: the number 2 is contained within the “b” item in the list. Look up how to subset lists from the lecture notes.
To answer these questions, you will need gapminder data loaded. Below I’ll load it from the web. When you run it you should see a ‘gapminder’ data object in the ‘Environment’ on the top right of RStudio.
gapminder <- read.csv("https://raw.githubusercontent.com/swcarpentry/r-novice-gapminder/gh-pages/_episodes_rmd/data/gapminder-FiveYearData.csv")
Fix each of the following common data frame subsetting errors: WRAP the answers in the head() function to reduce the output to the console and log. For example, to get the first three rows and 2-3 columns:
Extract observations collected for the year 1957
gapminder[gapminder$year = 1957,]
Extract all columns except 1 through to 4
gapminder[,-1:4]
Extract the rows where the life expectancy is longer the 80 years
gapminder[gapminder$lifeExp > 80]
Extract the first row, and the fourth and fifth columns (lifeExp
and gdpPercap
).
gapminder[1, 4, 5]
Advanced: extract rows that contain information for the years 2002 and 2007
gapminder[gapminder$year == 2002 | 2007,]