[R] store result of loop in df

Berend Hasselman bhh at xs4all.nl
Fri Jul 29 11:10:22 CEST 2016


> On 29 Jul 2016, at 10:52, 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?
> 

How about

for (i in 1:nrow(df)){
 df$VAR[i] <- (binom.test(df[i,1],df[i,2],0.065))$estimate[[1]]
} 

Berend Hasselman



More information about the R-help mailing list