【问题标题】:Programmatically change class to custom class以编程方式将类更改为自定义类
【发布时间】:2016-11-10 09:47:43
【问题描述】:

使用包openxlsx 准备将数据框写入excel 工作簿,我可以运行openxlsx's vignette 中的示例,使用每列的列方式更改变量的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"

为了使用我自己的数据集,我想使用dplyr 来更改名称与给定字符串匹配的列的类别(如下所示)。

到目前为止我已经尝试过:

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"

我感觉setAs 函数可能与我的问题有关,但我不知道如何使用它。

感谢您的帮助

【问题讨论】:

    标签: r excel dplyr


    【解决方案1】:

    fn_toPercentage 中似乎有错误。它应该是这样的:

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

    【讨论】:

    • 非常感谢格雷戈里!
    猜你喜欢
    • 2023-01-10
    • 2011-12-27
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2015-04-21
    • 1970-01-01
    相关资源
    最近更新 更多