0

I have a data table called e.table that contains a column named Entity and another named Equity. One of the rows in the Entity column is named total count, and it sums all the Equity values of the other rows. I have written this line that does this calculation:

e.table[e.table$Entity != "Total count", sum(e.table$Equity)]

and if I print it, it gives me what I want, but if I do this:

e.table <- e.table[e.table$Entity != "Total count", sum(e.table$Equity)]

or this:

e.table[, Equity :=vapply(Equity, e.talbe[e.table$Entity != "Total count", sum(e.table$Equity)]]

I don't get the updated value for Total count.

What I actually want is to ask how I can apply this line of code into the table so that the table is updated with this new value of total count.

joasa
  • 946
  • 4
  • 15
  • 35
  • [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data, since right now we can't run any of your code or see what you're getting – camille Nov 21 '19 at 15:18

2 Answers2

1

You need to store it in the variable rather than the entire table. Try doing this:

e.table[e.table$Entity = "Total count"]$Equity <- e.table[e.table$Entity != "Total count", sum(e.table$Equity)]
Anisha Singhal
  • 115
  • 1
  • 7
1

From the fact that you say "data table" and use the operator :=, I understand that you are using package data.table.

Let's assume your data looks like this:

library(data.table)
e.table <- data.table(Entity=c("a", "b", "c", "Total count"), Equity=c(1, 3, 6, 10))
e.table
#         Entity Equity
# 1:           a      1
# 2:           b      3
# 3:           c      6
# 4: Total count     10

and let's also assume that at some point someone from the outside world adds a row without updating total count, and it becomes something like this:

e.table <- data.table(Entity=c("a", "b", "c", "d", "Total count"), Equity=c(1, 3, 6, 10, 10))
e.table
#         Entity Equity
# 1:           a      1
# 2:           b      3
# 3:           c      6
# 4:           d     10
# 5: Total count     10

and you're looking for a way to update this Total count value.

This should do the trick:

e.table[Entity=="Total count", Equity := e.table[Entity!="Total count", sum(Equity)]]
e.table
#         Entity Equity
# 1:           a      1
# 2:           b      3
# 3:           c      6
# 4:           d     10
# 5: Total count     20
Vongo
  • 1,325
  • 1
  • 17
  • 27