Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
250 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...