我正在使用openxlsx包创建excel文件。要将列格式化为美元,示例说要将类设置为“货币”:
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) <-‘货币’时,我能够在现有的dataframe中更改这个类。
我有一种感觉,这是一个很好的机会来了解更多的课程(我复习了高级R部分的课程,但无法与我的问题建立联系)
发布于 2017-08-09 01:08:32
在上面回复@Frank的评论:
as.currency <- function(x) {class(x) <- "currency"; x}
iris %>% mutate_all(funs(as.currency(.))) %>% glimpse观察:150个变量:5美元Sepal.Length 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、. Sepal.Width 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 1.4、1.4、1.3、1.5、1.4、1.7、1.4、1.5、1.4、1.5、1.6、1.4、1.1、1.2、1.5、1.3、1.31.4,1.7,1.5,.$ Petal.Width 0.2,0.2,0.2,0.2,0.2,0.4,0.2,0.2,0.1,0.2,0.2,0.1,0.2,0.4,0.4,0.3,0.3,0.3美元物种 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.
发布于 2017-08-08 23:52:00
可以使用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" 发布于 2017-08-08 23:23:49
我不知道如何使用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"https://stackoverflow.com/questions/45579287
复制相似问题