小编Dav*_*dws的帖子

R - 使用 mutate 分配类

我正在使用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 部分,但无法与我的问题建立联系)

r dplyr

2
推荐指数
1
解决办法
2995
查看次数

标签 统计

dplyr ×1

r ×1