我问了一个关于data.table
的上一个问题(r - data.table - Why is the data.table result 1 numeric value when it should be rounded to 3 decimal places?)并显示了数字结果。评论提示我只使用by = cyl
,但不会给我dplyr
结果。因此,我在这里提出一个新问题。
如何使用dplyr
获得相同的结果(请参阅下面的data.table
代码)?
# using dplyr
mtcars1 %>%
group_by(cyl) %>%
select(disp) %>%
mutate(displace = round(disp / sum(disp), digits = 3))
# Adding missing grouping variables: `cyl`
# Source: local data frame [32 x 3]
# Groups: cyl [3]
#
# cyl disp displace
# <dbl> <dbl> <dbl>
# 1 4 108.0 0.093
# 2 4 146.7 0.127
# 3 4 140.8 0.122
# 4 4 78.7 0.068
# 5 4 75.7 0.065
# 6 4 71.1 0.061
# 7 4 120.1 0.104
# 8 4 79.0 0.068
# 9 4 120.3 0.104
# 10 4 95.1 0.082
# # ... with 22 more rows
我试过这个(参见上面提到的上一篇文章):
# Group cars by number of cylinders and the computed share of displacement
# using data.table
setkey(mtcars2, "cyl")
mtcars2[ , .(displace = round(disp / sum(disp), digits = 3)), by = list(cyl, disp)]
# cyl disp displace
# 1: 4 108.0 1
# 2: 4 146.7 1
# 3: 4 140.8 1
# 4: 4 78.7 1
# 5: 4 75.7 1
# 6: 4 71.1 1
# 7: 4 120.1 1
# 8: 4 79.0 1
# 9: 4 120.3 1
# 10: 4 95.1 1
# cyl disp displace
这在这里不起作用(尽管它有效:How to group data.table by multiple columns?)
mtcars2[ , displace = round(disp / sum(disp), digits = 3), by = list(cyl, disp)]
# Error in `[.data.table`(mtcars2, , displace = round(disp/sum(disp), digits = 3), :
# unused argument (displace = round(disp/sum(disp), digits = 3))
这并不能提供我想要的所有列(如r - data.table - Why is the data.table result 1 numeric value when it should be rounded to 3 decimal places?中所述):
mtcars2[ , .(displace = round(disp / sum(disp), digits = 3)), by = cyl]
谢谢。
答案 0 :(得分:3)
在data.table
中使用:=
语法时,即不使用j
时,您可以在结果中添加列mtcars2[,.(displace = round(disp / sum(disp), digits = 3), disp), by = cyl]
# cyl displace disp
# 1: 6 0.125 160.0
# 2: 6 0.125 160.0
# 3: 6 0.201 258.0
# 4: 6 0.175 225.0
# 5: 6 0.131 167.6
# 6: 6 0.131 167.6
# 7: 6 0.113 145.0
# ...
列中的列}:
Casing = {}
Casing.__index = Casing
sentArray = {}
function Casing.create(x, y, z)
if x ~= nil and y ~= nil and z ~= nil then
local _casing = {}
setmetatable(_casing,Casing)
--etc.
return _casing
end
end