r - Programmatically change class to custom class -


using package openxlsx prepare writing of dataframe excel workbook, able run example in openxlsx's vignette using column per column way change variable's class.

## data.frame write df <- data.frame("date" = sys.date()-0:4, "logical" = c(true, false, true, true, false), "currency" = paste("$",-2:2), "accounting" = -2:2, "hlink" = "http://cran.r-project.org/", "percentage" = seq(-1, 1, length.out=5), "tinynumber" = runif(5) / 1e9, stringsasfactors = false)  ## below comes custom class assignation used excel formatting class(df$currency)   <- "currency" class(df$accounting) <- "accounting" class(df$hlink)      <- "hyperlink" class(df$percentage) <- "percentage" class(df$tinynumber) <- "scientific"  ## works ! class(df$percentage) [1] "percentage" 

in order work own dataset use dplyr change class of columns name matching given string (as below).

what i've tried far:

require(tidyverse) fn_topercentage <- function(x){class(x)<-"percentage"}  df2 <- df %>%   mutate_at(vars(starts_with("percent")),funs(fn_topercentage))  ## check: lapply(df2,class) $date [1] "date"  $logical [1] "logical"  $currency [1] "character"  $accounting [1] "integer"  $hlink [1] "character"  ## failed !     $percentage [1] "character"  $tinynumber [1] "numeric" 

i have feeling function setas might relevant problem, cannot figure out how use it.

thanks help

looks there error in fn_topercentage. should looks this:

fn_topercentage <- function(x){     class(x)<-"percentage"     x } 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -