1
使用程序包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
可能是有關我的問題,但我無法弄清楚如何使用它。
感謝您的幫助
非常感謝Gregory! – Cazz