R:按在数据表中创建的新变量排序 [英] R: Order by new variable created in Data table
本文介绍了R:按在数据表中创建的新变量排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图理解为什么不能按我在同一行中创建的新变量进行排序。
I am trying to understand why can't I order by a new variable that I create in the same line.
当前我需要写两行,一个
Currently I need to write two lines, one for creating the new variable and then for ordering it.
可以在 data.table 的同一行中完成此操作吗?
Can this be done in the same line in data.table:
DF <- data.table(ID = c(1,2,1,2,1,1,1,1,2), Value = c(1,1,1,1,1,1,1,1,1))
newDF <- DF[order(-Count), .(Count = .N), by = ID]
# Gives error: Error in eval(v, x, parent.frame()) : object 'Count' not found
# Works Correctly
newDF <- DF[, .(Count = .N), by = ID]
newDF <- newDF[order(-Count)]
> newDF
ID Count
1: 1 6
2: 2 3
推荐答案
您只需将两个操作链接在一行中即可,
You can simply chain both of the operations in a single line,
DF[, .(Count = .N), by = ID][order(-Count)]
这篇关于R:按在数据表中创建的新变量排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文