将 data.table 链分成两行代码以提高可读性 [英] Break data.table chain into two lines of code for readability

查看:19
本文介绍了将 data.table 链分成两行代码以提高可读性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 Rmarkdown 文档,并被告知严格限制最大列数(边距列)为 100.在文档的代码块中,我使用了许多不同的包,其中包括 data.表.

I'm working on a Rmarkdown document, and was told to strictly limit to a maximum number of columns (margin column) of 100. In the document's code chunks I used many different packages, among which is data.table.

为了遵守限制,我可以拆分链(甚至是长命令),例如:

In order to comply with the limit I can split chains (and even long commands) like:

p <- ggplot(foo,aes(bar,foo2))+
       geom_line()+
       stat_smooth()
bar <- sum(long_variable_name_here,
         na.rm=TRUE)
foo <- bar %>% 
         group_by(var) %>%
         summarize(var2=sum(foo2))

但我无法拆分 data.table 链,因为它会产生错误.我怎样才能实现这样的目标?

but I can't split a data.table chain, as it produces an error. How can I achieve something like this?

bar <- foo[,.(long_name_here=sum(foo2)),by=var]
           [order(-long_name_here)]

当然,最后一行会导致错误.谢谢!

Last line, of course, causes an error. Thanks!

推荐答案

你必须在每一行的[] 之间给出一个返回值.如何将 data.table 代码分成几行的示例:

You have to give a return between the [ and ] of each line. An example for how to divide your data.table code over several lines:

bar <- foo[, .(long_name_here = sum(foo2)), by = var
           ][order(-long_name_here)]

您还可以在每个逗号之前/之后返回.逗号前返回的示例(我的偏好):

You can also give a return before / after each comma. An example with a return before the comma (my preference):

bar <- foo[, .(long_name_here = sum(foo2))
           , by = var
           ][order(-long_name_here)
             , long_name_2 := long_name_here * 10]

有关扩展示例,请参阅 此答案

See this answer for an extended example

这篇关于将 data.table 链分成两行代码以提高可读性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆