Changing Variable Values with mutate()
The mutate()
function from the dplyr
package is a powerful tool for creating and modifying variables within a data frame.
1. Changing Values Based on a Condition
You can use mutate() along with ifelse() to change the values of a variable based on a condition.
# Change 'score' to 100 if 'age' is greater than 40
data <- data %>%
mutate(score = ifelse(age > 40, 100, score))
# Display the updated data frame
print(data)
Output:
id name age score
1 1 Ali 25 88
2 2 Boby 30 92
3 3 Charles 35 85
4 4 David 40 87
5 5 Eva 45 100
2. Using mutate() with Multiple Conditions
You can use case_when() for more complex conditional logic.
# Change 'score' based on multiple conditions
data <- data %>%
mutate(
score = case_when(
age <= 30 ~ score + 10,
age > 30 & age <= 40 ~ score + 5,
age > 40 ~ score + 15
)
)
# Display the updated data frame
print(data)
Output:
id name age score
1 1 Ali 25 98
2 2 Boby 30 102
3 3 Charles 35 90
4 4 David 40 92
5 5 Eva 45 115
3. Modifying Multiple Variables
You can modify multiple variables within a single mutate() call.
# Change 'age' and 'score' simultaneously
data <- data %>%
mutate(
age = age + 1,
score = score * 1.1
)
# Display the updated data frame
print(data)
Output:
id name age score
1 1 Ali 26 107.8
2 2 Boby 31 112.2
3 3 Charles 36 99.0
4 4 David 41 101.2
5 5 Eva 46 126.5
How to Change value of variable with dplyr
The Dplyr package in R is a powerful tool for data manipulation and transformation. It provides a set of functions that allow you to perform common data manipulation tasks concisely and efficiently. One of these tasks is changing the value of a variable within a data frame. This article will guide you through various methods to change the value of a variable using dplyr.
Contact Us