[R] store result of loop in df

Jim Lemon drjimlemon at gmail.com
Fri Jul 29 11:19:07 CEST 2016


Hi Alain,
You are probably storing the result, replicated five times, in df$VAR.
Each cycle of the loop replaces the last value with the current value.
If you really want the entire output of binom.test in the last column:

multi.binom.test<-function(xs,ns) {
  reslist<-list()
 for(i in 1:length(xs)) reslist[[i]]<-binom.test(xs[i],ns[i])
 return(reslist)
}
df$VAR<-multi.binom.test(df$x,df$n)

I suspect that you probably want only the p.value element.

Jim


On Fri, Jul 29, 2016 at 6:52 PM, Alain D. via R-help
<r-help at r-project.org> wrote:
> Dear list,
>
> I have a dataframe df:
>
> df<-data.frame(x=c(5,32,18,3,17), n=c(11,200,432,20,60))
>
> Now I want to run n=nrow binom.test() with x being the number of success and n
> the number of trials and then store the results as a new VAR in df.
>
> I tried
>
>   for (i in 1:nrow(df)){
>   df$VAR<-(binom.test(df[i,1],df[i,2],0.065))$estimate[[1]]
> }
>
> but bin does only contain the last result.
>
> What is wrong with my code? Can anyone help?
>
> Thank you in advance.
>
> Alain
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list