3つの異なるメソッド(method1、method2、method0)を持つ2つのサイト(A & B)、2つのグループ(グループ1 & 2)からの推定値を含むデータフレームdfがあります。コントロールまたはベースライングループを持つデータフレームのR計算
df1<-data.frame(site=rep("A", 21),
group=rep("group1", 21),
estimate=c(rnorm(10, 15, 3), rnorm(10, 2, 7), rnorm(1, 6, 2)),
method=c(rep(c("method1","method2"),each=10),"method0"))
df2<-data.frame(site=rep("B", 21),
group=rep("group2", 21),
estimate=c(rnorm(10, 13, 3), rnorm(10, 5, 7), rnorm(1, 9, 2)),
method=c(rep(c("method1","method2"),each=10),"method0"))
df<-rbind(df1, df2)
df
site group estimate method
1 A group1 15.1561073 method1
2 A group1 14.4067422 method1
3 A group1 12.7428921 method1
..........
41 B group2 0.3548033 method2
42 B group2 10.5820482 method0
Iは、ベースライングループとしてmethod0を使用し、各サイト/グループの各推定値に対する相対パーセンテージバイアス(RB)を算出したいです。
#for each site and group of estimate
rb<-(estimate-estimate0)/estimate0*100%
# where estimate0 is the estimate of method0 of that certain site/group
各サイト/グループには1つしかありません。私はシンプルな関数を書こうとしていて、各サイト/グループに対してapply
を使用しましたが、うまくいきませんでした。
fun.rb<-function(df, basline){
control<-df$method==baseline
rb<-(df$estimate-control$estimate)/(control$estimate)*100%
return(rb)
}
df %>% group_by(site,group) %>% mutate(rb=fun.rb, baseline="method0")
すべての入力とコメントは非常に高く評価されています。
うわー、それは素晴らしいですね。私の機能を固定してくれてありがとう。 – lamushidi
私はあなたが実際に関数を必要としないことを指摘し、関数内の計算で関数呼び出しを置き換えることで、インラインで全体を行うことができます。 – yeedle
はい、もちろんです。そうすれば、コードをもっときれいにすることができます。どうもありがとう。 – lamushidi