Home » How to Use the transform Function in R (3 Examples)

How to Use the transform Function in R (3 Examples)

by Erma Khan

You can use the transform() function in base R to modify existing columns or add new columns to a data frame.

This function uses the following basic syntax:

transform(df, my_column = my_column_transformed)

The following examples show how to use this function in different scenarios with the following data frame in R:

#create data frame
df frame(pos=c('G', 'G', 'F', 'F', 'C'),
                 points=c(23, 29, 33, 14, 10),
                 assists=c(7, 7, 5, 9, 14))

#view data frame
df

  pos points assists
1   G     23       7
2   G     29       7
3   F     33       5
4   F     14       9
5   C     10      14

Example 1: Use transform() to Modify Existing Column

The following code shows how to use the transform() function to modify the existing points column:

#divide existing points column by 2
df_new 2)

#view new data frame
df_new

  pos points assists
1   G   11.5       7
2   G   14.5       7
3   F   16.5       5
4   F    7.0       9
5   C    5.0      14

Notice that each value in the existing points column was divided by two and all other columns remained unchanged.

Example 2: Use transform() to Add One New Column

The following code shows how to use the transform() function to add a new column called points2:

#add new column called points2
df_new 2)

#view new data frame
df_new

  pos points assists points2
1   G     23       7      46
2   G     29       7      58
3   F     33       5      66
4   F     14       9      28
5   C     10      14      20

Notice that the new column has been added to the data frame and all other existing columns remained the same.

Example 3: Use transform() to Add Multiple New Columns

The following code shows how to use the transform() function to add two new columns called points2 and assists2:

#add new columns called points2 and assists2
df_new 2,
                    assists2 = assists * 2)

#view new data frame
df_new

  pos points assists points2 assists2
1   G     23       7      46       14
2   G     29       7      58       14
3   F     33       5      66       10
4   F     14       9      28       18
5   C     10      14      20       28

Notice that two new columns have been added to the data frame and all other existing columns remained the same.

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Use length() Function in R
How to Use cat() Function in R
How to Use substring() Function in R

Related Posts