私は前の質問(r - data.table - Why is the data.table result 1 numeric value when it should be rounded to 3 decimal places?)について約data.table
と数値結果の表示を求めました。コメントは私がただby = cyl
を使用することを示唆しますが、それは私にdplyr
の結果を与えません。したがって、私はここで新しい質問をしています。r - data.table - 複数の列によるデータtableの結果を丸めて返します。
data.table
と同じ結果(下記のdplyr
コードを参照)を得るにはどうすればよいですか?
# 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
私は、この(上記の以前の記事を参照してください)試してみました:(それは働いていますが、:How to group data.table by multiple columns?を)これは、ここでは動作しません
# 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
を
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))
これは」doesnの(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]
ありがとうございます。
'mtcars2 [、(変位= round(disp/sum(disp)、digits = 3)、disp)、by = cyl] '結果を保持したい場合は、' disp'列を 'j'位置のリストにラップすることができます。 – Psidom
@Psidomコメントを回答にすることはできますか?ありがとうございました。それは完璧に働いた! – iembry