3

I'm not use to work with data.table and need some help for doing this type of operations

My data :

library(data.table)

x = c(rep('a', 3), rep('b', 4), 'c')

y = c(1, 2, 1, 4, 4, 2, 4, 5)

dt = data.frame(x , y)

My operation : I want to groupby the x variable, and sum on unique value of y

setDT(dt)[, sm := sum(y), by = list(x)]

The output is :

   x y sm
1: a 1  4
2: a 2  4
3: a 1  4
4: b 4 14
5: b 4 14
6: b 2 14
7: b 4 14
8: c 5  5

But I want :

   x y sm
1: a 1  3
2: a 2  3
3: a 1  3
4: b 4  6
5: b 4  6
6: b 2  6
7: b 4  6
8: c 5  5

I probably have to use the .SD but I dont know how !

Thanks for help

4 Answers 4

2

You could sum unique values.

library(data.table)
setDT(dt)[, sm := sum(unique(y)), x]
dt

#   x y sm
#1: a 1  3
#2: a 2  3
#3: a 1  3
#4: b 4  6
#5: b 4  6
#6: b 2  6
#7: b 4  6
#8: c 5  5
Sign up to request clarification or add additional context in comments.

1 Comment

Thnaks exactyly what I want
1

One option could be:

setDT(dt)[, sm := sum(y[!duplicated(y)]), by = x]

   x y sm
1: a 1  3
2: a 2  3
3: a 1  3
4: b 4  6
5: b 4  6
6: b 2  6
7: b 4  6
8: c 5  5

Comments

1
library(data.table)
dt[,.(sum(unique(y))),by=x]

2 Comments

Does this add anything to Ronak Shah's solution?
not exactly what I want, I want to keep the dataframe :)
1

Another solution (convoluted, but fun):

dt[, sm := unique(dt)[, sum(y), x][.SD, on = "x", V1]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.