递归应用dollar_format以获取列表中的美元格式

时间:2017-01-12 05:59:08

标签: r dplyr

我是R的初学者。所以,如果对你们这些人来说太容易了,我很抱歉。我有一个列表,我想将其中一列(" Value")转换为美元格式。我很感激任何帮助。

我试了lapply()但没有成功。

这是我的数据:

dput(Input_File)
structure(list(Zone = c("East", "East", "East", "East", "East", 
"East", "East", "West", "West", "West", "West", "West", "West", 
"West"), Fiscal.Year = c(2016, 2016, 2016, 2016, 2016, 2016, 
2017, 2016, 2016, 2016, 2017, 2017, 2018, 2018), Transaction.ID = c(132, 
133, 134, 135, 136, 137, 171, 171, 172, 173, 175, 176, 177, 178
), L.Rev = c(30000, 20000, 23400, 23423, 2344, 452343, 23445, 
234, 45234, 23, 234345, 43534, 23421, 345345), L.Qty = c(234253, 
2342, 12334, 234253, 2342, 12334, 234253, 2342, 12334, 234234, 
223423, 234234, 43534, 432423), A.Rev = c(17253, 11117, 19751, 
10457, 11820, 14607, 14512, 16676, 12189, 11714, 12243, 18506, 
10500, 17793), A.Qty = c(19245, 17584, 18267, 19371, 19867, 13359, 
16932, 11541, 13434, 14409, 13908, 11042, 14632, 17332), I.Rev = c(17775, 
14452, 18459, 19481, 18463, 16566, 11749, 19208, 12244, 15344, 
15561, 16261, 11977, 11643), I.Qty = c(16441, 10409, 14249, 11737, 
11439, 11714, 18159, 18523, 17653, 14573, 16571, 13127, 12152, 
12692)), .Names = c("Zone", "Fiscal.Year", "Transaction.ID", 
"L.Rev", "L.Qty", "A.Rev", "A.Qty", "I.Rev", "I.Qty"), row.names = c(NA, 
14L), class = "data.frame")

这是我的代码:

Output<-Input_File %>%
gather(Rev_Qty,Value, L.Rev:I.Qty)  %>%
separate(Rev_Qty, into=c("L.A","Rev.Qty")) %>% 
split(.,list(.$Zone,.$Rev.Qty,.$Fiscal.Year),drop = TRUE) %>%
lapply(.,function(x) {scales::dollar_format()(.[6])})

我收到以下错误:

Error in UseMethod("round_any") : 
  no applicable method for 'round_any' applied to an object of class "list" 

预期输出 我不知道如何创建一个包含我想要的输出的列表,因为我不知道如何递归地应用dollar_format(),但这就是我可以说的:它会是这样的运行以下代码:

Output<-Input_File %>%
    gather(Rev_Qty,Value, L.Rev:I.Qty)  %>%
    separate(Rev_Qty, into=c("L.A","Rev.Qty")) %>% 
    split(.,list(.$Zone,.$Rev.Qty,.$Fiscal.Year),drop = TRUE)

列中的数字&#34;值&#34;列表Output中的10个数据帧中的每一个都将以$格式表示。输出必须是10个数据帧的列表。例如,这里的代码显示了列表中第一个数据帧的第六列(Value)如何:

a<-Output[[1]]$Value
scales::dollar_format()(a)

Output列表的每个数据框中,通常会有其他列。我很感激任何帮助。如果有任何问题,请告诉我。

1 个答案:

答案 0 :(得分:1)

如果我们使用匿名函数调用,请使用x[[6]]代替.[6]

Input_File %>%
     gather(Rev_Qty,Value, L.Rev:I.Qty)  %>%
     separate(Rev_Qty, into=c("L.A","Rev.Qty")) %>% 
     split(.,list(.$Zone,.$Rev.Qty,.$Fiscal.Year),drop = TRUE) %>%
     lapply(.,function(x) {x[[6]] <- scales::dollar_format()(x[[6]])
                   x})

或者没有map(来自purrr

的匿名电话
library(purrr)
Input_File %>%
      gather(Rev_Qty,Value, L.Rev:I.Qty)  %>%
      separate(Rev_Qty, into=c("L.A","Rev.Qty")) %>% 
      split(.,list(.$Zone,.$Rev.Qty,.$Fiscal.Year),drop = TRUE) %>%
       map(~mutate(., Value = scales::dollar_format()(Value)))