Dear Alain,

The problem is that you save the results of each iteration in df$VAR. So obviously, you overwrite df$VAR at each iteration.

What you need to do it to create an empty vector that contains the right number of elements and then iteratively fill this list. You can then combine df and that vector

That would do it:
results <- vector(mode="numeric", length=nrow(df))
for (i in seq_along(results)){
    results[i] <- binom.test(df[i,1],df[i,2],0.065)$estimate[[1]]

}
df$VAR1 <- results

You could also use apply():
foo <- function(x) binom.test(x[[1]],x[[2]],0.065)$estimate
df$VAR2 <- apply(df[,1:2], 1, FUN=foo)

identical(df$VAR1, df$VAR2)

HTH,
Ivan

--
Ivan Calandra, PhD
Scientific Mediator
University of Reims Champagne-Ardenne
GEGENAA - EA 3795
CREA - 2 esplanade Roland Garros
51100 Reims, France
+33(0)3 26 77 36 89
ivan.calan...@univ-reims.fr
--
https://www.researchgate.net/profile/Ivan_Calandra
https://publons.com/author/705639/

Le 29/07/2016 à 10:52, Alain D. via R-help a écrit :
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@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.


______________________________________________
R-help@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.

Reply via email to