Let's continue our adventure with dplyr package. In the previous article I introduced select() function which select a subset of columns. Today we will focus on how to pick the observation and add a new column. We will continue using mtcars dataset which is included in your R base program.
Also I would like to say that all the posts I publish here requires basic knowledge of R and R Studio program. If you are totally new in R and don't have it installed on your computer I strongly recommend you to find some on-line tutorials and start with R fundamentals.
library(dplyr)data("mtcars")
head(mtcars)
Now, let's introduce function:
filter() filter a subset of rows (pick the observation)
filter() with between() function:
filter(.data=mtcars,between(mpg,18,20)) #filter rows where values of mpg are between 18 and 2slice() select rows using their position - rows IDs (integer location)
slice(.data = mtcars, 1:3) #choosing first three rows of the mtcars dataset
mutate() compute a new column (add a new variable while keeping the base variables)
head(mutate(.data=mtcars,new=mpg/cyl)) #add a new variable while keeping the base variables
transmute() calculates new variables while dropping the base ones.
head(transmute(.data=mtcars,new=mpg/cyl)) #calculates new variables while dropping the base ones.
new1 3.500000
2 3.500000
3 5.700000
4 3.566667
5 2.337500
6 3.016667

Comments
Post a Comment