John Beieler

PhD Student in Political Science

R Magic and Bootstrapped T-test

Following up on my last post, I wanted a way to test my bootstrapped t-test function against the regular t-test function in R. While I was able to do this by copy-pasting between R and a Python shell, this was less than ideal. I then saw, however, a post by Christopher Fonnesbeck that discussed the use of the rmagic function in ipython, which can be loaded using the %load_ext magic function. So, with this in mind, I decided to test it out using a comparison between my bootstrap function and the t.test function in R. As a note, the rmagic extension requires rpy2, so just pip install rpy2 and you should be good to go.

1
2
3
4
5
6
7
8
9
10
import bootFunction

%load_ext rmagic
%R treatment = c(24,25,28,28,28,29,29,31,31,35,35,35)
%R control = c(21,22,24,27,27,28,29,32,32)
%Rpull treatment control

bootFunction.bootstrap_t_test(treatment, control, direction = "greater")

%R print(t.test(treatment, control, alternative = "greater"))

I first import the set of functions from the bootFunction. I then load the rmagic extension using the %load_ext magic function. Using the %R magic function I then defined two vectors of data, treatment and control, in the R space. I then used %Rpull to pull the two vectors from the R space into the Python shell. The two variables become structured numpy arrays. I then perform the bootstrapped t-test as described in the earlier post. Finally, using the %R magic function again, I print out the results of the t.test function in R using the same data. The p-values aren’t exactly the same, as is to be expected, but are at least within the same ballpark (the R t-test gives .05, while the boostrap function has returned a range between .05 and .03).