r dt(dataTable)中货币,数字和百分比的条件(行)形成(划分)
我的DT输出(微光)中有一个具有数值的列,该数字值依赖于另一列。有些值是百分比,有些是货币,有些是普通数字。
例如,我想转到此输入...
DefaultFormat | 值 |
---|---|
PCT | 12345.67 |
美元 | 12345.67 |
编号 | 12345.67 |
...进入此DT输出:
DefaultFormat | Value |
---|---|
PCT | 123.45 |
% | $ |
编号 | 12,345.67 |
12,345 格式化()
和格式化()
函数可以完成这些相应格式中的我所需的工作,但它们会影响整个列而不是特定的单元格。另一方面,formatstyle()
可以基于另一列的特定单元格在列中定位特定的单元格,但我无法找到一种使其更改内容而不是样式的方法。
此外,我尝试使用formatStyle()
尝试设置类,希望在.css文件中我可以定位目标,例如.pctClass:
和.currencyClass。 :
之前,但它忽略了类属性。
获得formatStyle()
的有条件行为的好方法是什么?
I have column in my DT output (in Shiny) that has a numeric value whose units depend on another column. Some values are percentages, some are currency, and some are plain numbers.
For example, I would like to turn this input...
DefaultFormat | Value |
---|---|
PCT | 12345.67 |
DOLLAR | 12345.67 |
NUMBER | 12345.67 |
...into this DT output:
DefaultFormat | Value |
---|---|
PCT | 123.45% |
DOLLAR | $12,345 |
NUMBER | 12,345.67 |
The formatCurrency()
, formatPercentage()
and formatRound()
functions do what I need for each of these respective formats but they affect the entire column instead specific cells. On the other hand formatStyle()
can target specific cells in a column based on another column but I can't figure out a way to have it change the contents rather than the styles.
Furthermore, I tried setting the class using formatStyle()
in the hopes that in the .css file I could then target, e.g. .pctclass:after
and .currencyclass:before
but it ignores the class attribute.
What is a good way to get the conditional behavior of formatStyle()
but for numbers, percentages, and currencies?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:这是从此处借用的解决方案: https://stackoverflow.com/a/35657820/6851825
试图根据基础数据对格式化的列进行分类,而不是其多样的格式化外观。您可以通过使用未格式的助手列来处理排序来执行此操作:
例如,请注意
5 454%
即使在其他条目之前出现在其他条目之前,即使以后是字母表:EDIT: here's a solution borrowing from the approach here: https://stackoverflow.com/a/35657820/6851825
You are seeking to sort a formatted column based on the underlying data instead of its varied formatted appearance. You can do this by using an unformatted helper column to handle the sorting:
For example, note how
5 454%
appears before the other entries even though it is alphabetically later:(这不是
dt
- 特定的,目前尚不清楚这是否是必要的。)您可以分组或拆分并分配:
替代方案是使用
case_when
和它会产生非常相似的结果,但一次将工作一个字符串。此方法调用格式函数一次,每组 ,也许更有效。 (如果有必要,请给您。)(This is not
DT
-specific, it wasn't clear if that was a requirement.)You can group or split and assign:
An alternative would be to use
case_when
and it would come up with very similar results, but it will be working one string at a time; this method calls the format function once per group, perhaps a bit more efficient. (Over to you if that's necessary.)