[R] [FORGED] store result of loop in df

Rolf Turner r.turner at auckland.ac.nz
Fri Jul 29 11:20:30 CEST 2016


On 29/07/16 20:52, Alain D. via R-help 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?

Try:

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

(Actually I was amazed that this works without initializing df$VAR, but 
it *does* work!  There is no limit to the wondrous nature of R!)

BTW -- calling your data frame "df" is a bad idea.  There is a built-in
function named "df", and on occasion the result of naming some other 
object "df" can be mysterious errors accompanied by opaque error messages.

cheers,

Rolf Turner

-- 
Technical Editor ANZJS
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276



More information about the R-help mailing list