【发布时间】: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 函数可能与我的问题有关,但我不知道如何使用它。
感谢您的帮助
【问题讨论】: