2017-08-08 126 views
0

我正在使用openxlsx包創建excel文件。要格式化列美元,例子說給類設置爲「貨幣」:R - 使用mutate分配類

class(df$Currency) <- 'currency' 

不過,我想這是一次應用於許多列和貨幣百分比等重複一次,一次那是我最終的目標,但我到了那裏 - 這是我到目前爲止嘗試過的。

第一工作示例:

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" 

現在用dplyr和變異 嘗試1:

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

嘗試2:

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

這變得非常非常接近我想要但輸出是一個列表和as.data.frame和as.tbl都抱怨沒有方法等級爲「貨幣」。

當我使用類(df $ sales)< - '貨幣'時,我可以在現有數據框中更改類。

我有一種感覺,這是一個很好的機會,以瞭解更多關於類(我審查了關於類的高級R段,但不能讓我的問題的連接)

+1

定義'as.currency'和使用? – Frank

+0

謝謝弗蘭克 - 我很早就試過了,放棄得太快了 - 以下面提供的例子爲例,返回函數中的x正是我所需要的。 – Davidws

回答

3

爲了呼應@以上弗蘭克的評論:

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

iris %>% mutate_all(funs(as.currency(.))) %>% glimpse 
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... 
+0

謝謝!我很早就嘗試過,但沒有返回x。結合變異這個作品。我希望我可以創建一個函數爲我想要的格式列表創建這些函數,並使用這種方法應用每個函數。 – Davidws

1

我不知道如何做到這一點使用dplyr,但這是一種有效的方法。

# list the column names 
names <- colnames(df) 

# loop through the columns and assign the class 'currency' 
for (i in 1:length(names)){ 

    class(df[, names[i]]) <- 'currency' 
} 

lapply(df, class) 
$sales 
[1] "currency" 

$returns 
[1] "currency" 
2

它可以使用purrr,但其結果只能強制轉換爲數據幀,如果每列也從numeric繼承(即,既是貨幣和數字)。我不知道這對openxlsx是否足夠好。

dfr <- data.frame(x=1:10, y=1:10, z=1:10) 
library(purrr) 
as.data.frame(map(dfr, `class<-`, c("currency","numeric"))) 

sapply(x, class) 
    x   y   z   
[1,] "currency" "currency" "currency" 
[2,] "numeric" "numeric" "numeric" 
+0

謝謝,我甚至沒有想過用purrr一次做所有事情。我會看看openxlsx是否接受這個,但即使不是很好的方法。 – Davidws