-1

I am looking for a similar function/package in R to that of Data Table in MS Excel (What-If calculations). Currently I use Data tables in Excel extensively to do multiple calculations on thousands of rows of input data. I have attached a snapshot of the calculations being done in Excel Data Table:

enter image description here

In other words, all my formulae/calculations are in a single tab of spreadsheet, and all the input data in another tab (several thousand of rows). I use data table operation to calculate results for each row of this data set. This makes my spreadsheet tidy with all the calculations in only single tab. Now I am looking to implement the same using R. Any help on this is deeply appreciated.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Ravikk
  • 1
  • 2
  • Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – zx8754 Jul 25 '16 at 11:37
  • @zx8754 I have now added an image of the calculations from Excel Data table to make my question clearer. Tried my best to put across my query. – Ravikk Jul 25 '16 at 17:42
  • 1
    Assuming your input dataframe is named *df1*, we can calculate *Calc1* as: `df1$Calc1 <- df1$X * df1$Y`, for *Calc2*: `df1$Calc2 <- df1$Z / df1$Y`, and for *Calc3*: `df1$Calc3 <- df1$Z + df1$X`. – zx8754 Jul 25 '16 at 18:20

1 Answers1

1

First, let's make your problem reproducible:

df <- data.frame(case = 1:12,
                 x = seq(10, 120, by = 10),
                 y = seq(0.5, 1.6, by = 0.1),
                 z = seq(100, 210, by = 10))
head(df)
#   case  x   y   z
# 1    1 10 0.5 100
# 2    2 20 0.6 110
# 3    3 30 0.7 120
# 4    4 40 0.8 130
# 5    5 50 0.9 140
# 6    6 60 1.0 150

Then, we can solve this the traditional way:

df$calc1 <- df$x * df$y
df$calc2 <- df$z / df$y
df$calc3 <- df$z + df$x

head(df)
#   case  x   y   z calc1    calc2 calc3
# 1    1 10 0.5 100     5 200.0000   110
# 2    2 20 0.6 110    12 183.3333   130
# 3    3 30 0.7 120    21 171.4286   150
# 4    4 40 0.8 130    32 162.5000   170
# 5    5 50 0.9 140    45 155.5556   190
# 6    6 60 1.0 150    60 150.0000   210

Alternatively, you could use transform:

transform(df, calc1 = x / y, calc2 = z / y, calc3 = z + x)
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116