R - 使用 mutate 分配类

Dav*_*dws 2 r dplyr

我正在使用openxlsx包来创建 excel 文件。要将列的格式设置为美元,示例说明将类设置为“货币”:

class(df$Currency) <- 'currency'
Run Code Online (Sandbox Code Playgroud)

但是,我想将其应用于许多列一次,并为货币重复一次,一次为百分比等。这是我的最终目标,但我到达那里 - 这是我迄今为止尝试过的。

首先是工作示例:

df <- data.frame(sales = c(10, 20, 30, 40, 50), returns = c(-5, -10, -20, 0, 0))
class(df$sales) <- 'currency'
class(df$sales)
[1] "currency"
Run Code Online (Sandbox Code Playgroud)

现在使用 dplyr 并改变尝试 1:

df %>% 
mutate_all(`class<-`(., 'currency'))
Error: Can't create call to non-callable object
Run Code Online (Sandbox Code Playgroud)

尝试 2:

df <- df %>% 
`class<-`(., 'currency') 
df
$sales
[1] 10 20 30 40 50
attr(,"class")
[1] "currency"
Run Code Online (Sandbox Code Playgroud)

这更接近我想要的,但输出是一个列表,as.data.frame 和 as.tbl 都抱怨没有类“货币”的方法。

当我使用 class(df$sales) <- 'currency' 时,我只能更改现有数据框中的类。

我觉得这是一个了解更多类的好机会(我查看了关于类的高级 R 部分,但无法与我的问题建立联系)

Bri*_*ian 5

回应上面@Frank 的评论:

as.currency <- function(x) {class(x) <- "currency"; x}

iris %>%   mutate_all(funs(as.currency(.))) %>% glimpse
Run Code Online (Sandbox Code Playgroud)
Observations: 150
Variables: 5
$ Sepal.Length <S3: currency> 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.4, 4.8, 4.8, 4.3, 5.8, 5.7, 5.4, 5.1, 5.7, 5.1, ...
$ Sepal.Width  <S3: currency> 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3.0, 3.0, 4.0, 4.4, 3.9, 3.5, 3.8, 3.8, ...
$ Petal.Length <S3: currency> 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.6, 1.4, 1.1, 1.2, 1.5, 1.3, 1.4, 1.7, 1.5, ...
$ Petal.Width  <S3: currency> 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, ...
$ Species      <S3: currency> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
Run Code Online (Sandbox Code Playgroud)