Dave
Dave

Reputation: 3

Calculations on subsets of a data frame

Being new to R, I'm not sure how to go about solving this problem. Hope you can help.

I have a batch tree like the smaller version below.

ID  Batch   Input_Bx    Input_Wt    Imp_In  Imp_Out
4   B123/1  A123/1  75.1    0.08    0.06
12  B123/2  A123/1  25.2    0.08    0.04
3   B123/2  A123/2  50.1    0.02    0.04
9   B123/3  A123/2  50.0    0.02    0.05

What I want to do, is for every case where there are several input batches (Input_Bx) (e.g. B123/2), I want to multiple the Input_Wt by Imp_In, sum these products for all of the input batches and divide by the sum of the weights of the input batches. So for this fragment of the data table I would get:

Batch B123/1: (75.1 * 0.08) / (75.1) = 0.08
Batch B123/2: (25.5 * 0.08 + 50.1 * 0.02) / (25.2 + 50.1) = 0.04039841
Batch B123/3: (50.0 * 0.02) / (50.0) = 0.02

And produce a new df like:

Batch   Eff_Imp Imp_Out
B123/1  0.08    0.06
B123/2  0.04039841  0.04
B123/3  0.02    0.05

An example would be really helpful.

TIA.

Upvotes: 0

Views: 213

Answers (3)

Henrik
Henrik

Reputation: 67778

And the ddplyalternative:

library(plyr)

ddply(.data = df, .variables = .(Batch), summarize,
      Eff_imp = weighted.mean(Imp_In, Input_Wt),
      Imp_out = Imp_out[1]) # assuming one value of Imp_out within Batch

#    Batch    Eff_imp Imp_out
# 1 B123/1 0.08000000    0.06
# 2 B123/2 0.04007968    0.04
# 3 B123/3 0.02000000    0.05

Upvotes: 0

TheComeOnMan
TheComeOnMan

Reputation: 12905

You can use the data.table library -

dt <- data.table(df)
dt[,
  list(
    Eff_Imp = weighted.mean(x = Imp_in, w = Input_Wt )
  ),
  by = "Batch"
]

Upvotes: 0

alexis_laz
alexis_laz

Reputation: 13122

A way is the following:

#your data
DF <- read.table(text = 'ID  Batch   Input_Bx    Input_Wt    Imp_In  Imp_Out
4   B123/1  A123/1  75.1    0.08    0.06
12  B123/2  A123/1  25.2    0.08    0.04
3   B123/2  A123/2  50.1    0.02    0.04
9   B123/3  A123/2  50.0    0.02    0.05', header = T, stringsAsFactors = F)

#`split` your data based on `Batch` and calculate the `weighted.mean` in each 
w.m <- lapply(split(DF, DF$Batch), function(x) weighted.mean(x$Imp_In, x$Input_Wt))
#w.m
#$`B123/1`
#[1] 0.08

#$`B123/2`
#[1] 0.04007968

#$`B123/3`
#[1] 0.02

#combine, in a `data.frame`, the `Batch` / its weighted mean / its `Imp_Out`
#I suppose same `Batch`es have same `Imp_Out`s
newDF <- data.frame(cbind(names(w.m), unlist(w.m), 
                   aggregate(DF$Imp_Out, list(DF$Batch), unique)$x), row.names = NULL)

names(newDF) <- c("Batch", "Eff_Imp", "Imp_Out")
#newDF
#   Batch            Eff_Imp Imp_Out
#1 B123/1               0.08    0.06
#2 B123/2 0.0400796812749004    0.04
#3 B123/3               0.02    0.05

Upvotes: 1

Related Questions