Created
September 16, 2016 04:25
-
-
Save Jisoosong2017/91dcdbc2347c01d5e4cdd3d3dd63d99e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#LAb 1, Ji Soo Song | |
#Enable the dplyr package. | |
library(dplyr) | |
#Define a vector with 10 authors' last names. | |
authorLastName<-c('Kim','Andrews','McDonald','Johnson','Bryant','Stein','Rodriguez','Li','Ali','Watson') | |
#Define a vector with one book written by each author. | |
title<-c('Lost Men','Of Cites and States','Gone','International Comparisons','Why?','Dunkirk','Soar','Wings of Liberty','Abacus','Lilac') | |
#Define a vector with the publication years of the above books. | |
pYear<-c(1954,1933,1957,2003,2011,2014,1954,1957,1966,1954) | |
#Define a vector with the number of each book in stock. | |
nStock<-c(2,9,32,4,12,54,12,4,98,84) | |
#Define a vector with the price of each book. | |
dollarPrice<-c(11,12,23,8,22,7,21,14,18,12) | |
#Put together all defined vectors into a data frame. | |
bookstore<-data.frame(authorLastName,title,pYear,nStock,dollarPrice) | |
#Display unsorted data frame. | |
View(bookstore) | |
#Sort the original data frame by descending year of publication. | |
#And within same year of publication, sort by ascending order of author last name. | |
sortedBookstore <- bookstore%>%arrange(-pYear,authorLastName) | |
#Display the sorted data frame. | |
View(sortedBookstore) | |
#Mutate command used to add the sale price column. | |
#First check if a row has nStock above 10 and pYear below 1970. If true, apply a 50% discount. | |
#If false, check if a row has nStock less than 10 and pYear below 1970. If trre, apply a 25% discount. | |
#If false, check if a row has nStock more than 10 and pYear above 1970. If true, apply a 40% discount. | |
#In all other cases, keep original price as the sale price. | |
saleBookstore <- bookstore%>%mutate(saleDollarPrice=ifelse(nStock>10 & pYear<1970,dollarPrice*0.5,ifelse(nStock<10 & pYear<1970,dollarPrice*0.75,ifelse(pYear>1970 & nStock>10,dollarPrice*0.6,dollarPrice)))) | |
#Display the data frame with the sale price column added. | |
View(saleBookstore) | |
#Filter the rows where nStock is above 10 and pYear is below 1970 (i.e. the dicounted books). | |
subBookstore <- saleBookstore%>%filter(nStock>10 | pYear<1970) | |
#From these rows, select only the author last name, book title, and sale price columns. | |
subsubBookstore <- subBookstore%>%select(authorLastName,title,saleDollarPrice) | |
#Display this filtered and selected data frame. | |
View(subsubBookstore) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment