To apply a function to a specific set of variables from a dataframe in R, we can use the dplyr
library which provides an easy way to manipulate data frames.
Let's say we have a data frame called df
with columns col1
, col2
, col3
, col4
, and we want to apply a function my_function()
to columns col2
and col4
only.
We can use the select()
function from dplyr
to select the columns we want, and then apply the function using the mutate()
function. Here's an example code:
main.r91 chars6 lines
In this code, we first select col2
and col4
using the select()
function. Then, we use the mutate()
function to create a new column called result
which contains the result of applying my_function()
to col2
and col4
.
This will return a new data frame with the selected columns and the new result
column containing the output of my_function()
applied to these columns.
gistlibby LogSnag