Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

r - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...