R transform function with Example
R transform() function is used to manipulate data. The first variable is converted to a data frame.
This function is used to quickly and easily transform or modify the data frame.
R transform Syntax:
transform(data, value)
Parameters:
data: The data frame that will be changed
value: the data’s new updated value
We’ll start by creating a data frame with some random values.
For this R programming tutorial, the following data is utilized as a foundation.
Example 1:-Adding values into Existing variable
data<-data.frame(x1 = 1:10, x2 = 10:1) data
x1 x2 1 1 10 2 2 9 3 3 8 4 4 7 5 5 6 6 6 5 7 7 4 8 8 3 9 9 2 10 10 1
transformeddata <- transform(data, x1 = x1 + 1) transformeddata
x1 x2 1 2 10 2 3 9 3 4 8 4 5 7 5 6 6 6 7 5 7 8 4 8 9 3 9 10 2 10 11 1
We have added the value 1 to each of the members of variable x1 in the output, as you can see. A simple and powerful way to transform variables in data.frames!
Example 2:- Adding New Variable
Let’s try to add a new variable x3 into the existing data frame.
transformeddata2 <- transform(data, x3 = c(20:11)) transformeddata2
x1 x2 x3 1 1 10 20 2 2 9 19 3 3 8 18 4 4 7 17 5 5 6 16 6 6 5 15 7 7 4 14 8 8 3 13 9 9 2 12 10 10 1 11
We’re adding a new variable x3 to the prior data in the code above.
How to perform Rolling Correlation in R »
Subscribe to our newsletter!