Cazz Cazz - 24 days ago 12
R Question

Programmatically change class to custom class

using the package

openxlsx
to prepare the writing of a dataframe to an excel workbook, I am able to run the example in the openxlsx's vignette using the column per column way to change the variable's
class
.

## data.frame to 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 the custom class assignation used for 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 to work with my own dataset I would like to use
dplyr
to change the class of columns whose name is matching a given string (as below).

What I've tried so 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 the feeling that the function
setAs
might be relevant for my problem, but I cannot figure out how to use it.

Thanks for your help

Answer

Looks like there is an error in fn_toPercentage. It should looks like this:

fn_toPercentage <- function(x){
    class(x)<-"percentage"
    x
}
Comments