Home > Blockchain >  How to pass a user input as column name in the output table of a function in R
How to pass a user input as column name in the output table of a function in R

Time:11-02

I am trying to write a function in r. I have a data set that has month as col name. Each col consists of a set of number against a name. I wanted select one month and then multiply that column with ten and store it in a new column which is renamed with the month name e.g. Total_ (name of the month). Thank you

Name <- c("A"   ,"B"  ,"C"   ," D"  ,"E"  ,"F") 
Aug <-  c("12"   ,"12"  ,"2"   ," 5"  ,"12"  ,"12") 
Sep <- c("15"   ,"12"  ,"2"   ," 6"  ," 5"  ,"11" ) 
Oct <- c("8"   ,"12"  ,"2"   ," 5"  ," 5"  ," 6" )
June <- c("6"   ,"12"  ,"2"   ,"12"  ,"12"  ,"12")
 
data <- data.frame(Name,Aug,Sep,Oct,June)
my.function <- function(df,month) {
  name2 <- "aug"
  data <- data %>% select(1:1, contains(name2))
  d <- as.data.frame(data)
  d[is.na(d)] <- 0
  d[d==""] <- 0
  x <- paste0('sale_Total',name) # want to create a col name "Sale_Total_Month_selected" 
  d$(x) <- d$(name2)*10# this is not working :P
}

CodePudding user response:

Is this what you are looking for?

library(tidyverse)

my.function <- function(df, month){
  df |>
    select(Name, !!month)|>
    mutate(across(!!month, as.numeric),
           "sale_Total_{month}" := !!sym(month) * 10)
}

my.function(data, "Aug")
#>   Name Aug sale_Total_Aug
#> 1    A  12            120
#> 2    B  12            120
#> 3    C   2             20
#> 4    D   5             50
#> 5    E  12            120
#> 6    F  12            120
  •  Tags:  
  • r
  • Related