How to add calculated variables in R
Add calculated variables in R, To add new calculated variables to a data frame and remove all old variables, use the transmute() function in R.
The following is the fundamental syntax for this function.
df %>% transmute(var_new = var1 * 2)
In this example, we’ll make a new variable called var new by multiplying an existing variable called var1 by 2.
The examples below demonstrate how to use the transmute() function in R with the following data frame.
Let’s create a data frame
df <- data.frame(team=c('A1', 'B1', 'C1', 'D1', 'E1'), score=c(89, 70, 76, 78, 75))
Now we can view the data frame
team score 1 A1 89 2 B1 70 3 C1 76 4 D1 78 5 E1 75
Example 1: Create One New Variable using transmute()
The following code demonstrates how to create a new variable with transmute():
create a new variable called score1
df %>% transmute(score1 = score * 2)
score1 1 178 2 140 3 152 4 156 5 150
The original values in the score column are multiplied by two to get the score1 values.
It’s worth noting that the transmute() function doesn’t change the original data frame.
You must save the results of the transmute() method in a variable to save them in a new data frame:
Transmute results are saved in a variable.
df$score1<- df %>% transmute(score1 = score * 2)
View the results
team score score1 1 A1 89 178 2 B1 70 140 3 C1 76 152 4 D1 78 156 5 E1 75 150
The results of transmute() are now stored in a data frame.
Example 2: Create Multiple New Variables using transmute()
Transmute() can be used to create several new variables from existing variables, as shown in the following code.
Let’s create a multiple new variables.
df %>% transmute( score1 = score * 2, scoresquared = score^2, scorehalf = score / 2, name= paste0('team_', team) )
score1 scoresquared scorehalf name 1 178 7921 44.5 team_A1 2 140 4900 35.0 team_B1 3 152 5776 38.0 team_C1 4 156 6084 39.0 team_D1 5 150 5625 37.5 team_E1
Four new variables have been created, as you can see.