create a function with mutate in r

To create a function with mutate in R, you can use the dplyr package, which is a popular package for data manipulation.

Here's a basic example that creates a function using mutate:

main.r
library(dplyr)

# create a data frame
my_data <- data.frame(x = c(1, 2, 3, 4),
                      y = c(10, 20, 30, 40))

# create a function that squares a column
square_column <- function(data, column) {
  data %>% 
    mutate(!!column := !!sym(column) ^ 2)
}

# apply the function to the data frame
my_data_squared <- square_column(my_data, "y")
352 chars
15 lines

In this example, we first create a data frame called my_data with two columns (x and y). We then create a function called square_column that takes two arguments: data (the data frame to modify) and column (the name of the column to square).

Inside the function, we use !! and sym() to generate the column name dynamically, and use the ^ operator to square the column. Finally, we return the modified data frame.

To apply the function, we call square_column and pass in my_data and "y" as arguments. This produces a new data frame called my_data_squared where the y column has been squared.

gistlibby LogSnag