Home > other >  Using Function in R Programming
Using Function in R Programming

Time:11-21

I have a column named Interest with 10 values. I need to use function in R to multiply the values in the "Interest" column by 2 and to create a new column with the new multiplied values within the function.

Appreciate help, please.

I use the formula as :

col<-function(col){
  double<-col*2
  return(double)
}
df_col_double

Col = the name for the Interest column and double as the new column with the multipled values.

CodePudding user response:

You don't need to create a function and probably your question has been answered, but here is the way using tidyverse package and using hp column from mtcars dataset as example:

library(tidyverse)
mtcars %>% mutate(. , hp_2=hp*2)

hope this is what are you looking for.

CodePudding user response:

You could try using example data mtcars

col <- function(.data, col) {
  
  .data |> 
    dplyr::mutate(dplyr::across({{col}}, ~.x*2, .names = "double_{col}"))
}
col(mtcars,col = carb)

CodePudding user response:

base R you could use:

doublecol <- function(data,col) {
  data["new_col"]<-data[col]*2
  return(data)
}

doublecol(iris,"Sepal.Length" )
  •  Tags:  
  • r
  • Related