r code mutate
Sure! Here is an example of how to use the mutate()
function in R, along with an explanation of each step:
library(dplyr)
# Step 1: Create a data frame
data <- data.frame(name = c("John", "Sarah", "Michael"),
age = c(25, 30, 35),
salary = c(50000, 60000, 70000))
# Step 2: Use mutate() to create a new variable
data <- mutate(data, bonus = salary * 0.1)
# Step 3: Print the updated data frame
data
Explanation of each step:
We first create a data frame called
data
using thedata.frame()
function. This data frame contains three variables:name
,age
, andsalary
. Each variable is assigned a vector of values using thec()
function.We then use the
mutate()
function from thedplyr
package to create a new variable calledbonus
. In this case, we calculate the bonus as 10% of the salary by multiplying thesalary
variable by 0.1. Themutate()
function modifies the data framedata
by adding the new variablebonus
to it.Finally, we print the updated data frame
data
to see the result. Theprint()
function is not explicitly used here because R automatically prints the result of the last expression in the code block.
This code snippet demonstrates how to use the mutate()
function in R to add a new variable to a data frame based on calculations using existing variables. By understanding and using the mutate()
function, you can easily create new variables and perform data transformations in R.