我在Jupyter笔记本电脑上使用Mac OS Catalina,PyCharm。我正在尝试从python代码传递带有%% R的变量
import rpy2.rinterface
%load_ext rpy2.ipython
print(rpy2.__version__)
v=2
%%R -i v
print(v)
我收到此错误:
UsageError: Line magic function `%%R` not found.
Python 3.7.5 rpy2 3.2.2 R 3.5.1 导致此错误的原因是什么?如何解决?
答案 0 :(得分:1)
%%R
是一种细胞魔术,而不是线条魔术。您需要将其放置在新的单元格中。在PyCharm中,使用#%%
注释标记创建单元格。在PyCharm环境中的正确用法是:
#%%
%load_ext rpy2.ipython
v = 2
#%%
%%R -i v
print(v)
单元魔术以两个百分号(%%cell_magic_name
)开头,而行魔术则以一个百分号(%line_magic_name
)开始。您的错误消息表明您尝试在不同于单元格开头的位置使用单元格魔术,并且您的代码段没有(特定于PyCharm的)单元格分隔符,可以确认是这种情况。
rpy2提供了(完全相同的名称)单元格和行R魔术(%符号的数量是唯一的区别),但是单元魔术必须放在单元格的最开始-代码在其中该单元格将被解释为R。
答案 1 :(得分:0)
在尝试使用“ R magic”之前,请考虑使用 class Projectile:
def __init__(self, angle, velocity, height):
self.xpos = 0.0 # starting at the origin
self.ypos = height # y value will be the height which user specifies.
theta = math.radians(angle)
self.xvel = velocity * math.cos(theta) # cos will give us x axis parameter for velocity
self.yvel = velocity * math.sin(theta) # sin will give us y axis parameter for velocity
# the current position is stored in the instance xpos and ypos as this will update as projectile is fired
def getX(self):
return self.xpos
def getY(self):
return self.ypos
# now the updated position is stored. It must now be updated so elapsed time is reflected.
def update(self, time):
self.xpos = self.xpos + time * self.xvel # will track the motion of the projectile
yvel1 = self.yvel - 9.8 * time # acceleration of gravity on the porjectile in motion
self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
# position is the initial value plus time multiplied by the motion of the projectile in action.
self.yvel = yvel1 # updating the self.yvel variable after the calculation
A shot tracking class:
class shottracker(Projectile):
def __init__(self, win, angle, velocity, height):
"""win is the GraphWin to display the shot. angle, velocity, and height are initial projectile parameters"""
self.proj = Projectile(angle, velocity, height) # Attributes of the cannonball motion
self.marker = Circle(Point(0,height),3)
self.marker.setFill("black") # Cannonball color
self.marker.setOutline("black") # The cannonball outline color
self.marker.draw(win)
#self.cuplist = cuplist # tracker is establishing the cuplist
def update(self,dt): # This function updates the position and is responsible for the animation
self.proj.update(dt)
center = self.marker.getCenter()
dx = self.proj.getX() - center.getX()
dy = self.proj.getY() - center.getY()
#if dy == 0:
#for c in cuplist:
#if c.collision(dx) == True: #undraw cup
#cuplist.remove(c) # cup is removed
self.marker.move(dx,dy)
def getX(self):
return self.proj.getX()
def getY(self):
return self.proj.getY()
def undraw(self):
self.marker.undraw()
the rest of the code for creating the animation window:
class Button: # This was pretty much straight from Zelle. I'm not well versed in graphics.
def __init__(self, win, center, width, height, label):
w,h = width/2.0, height/2.0
x,y = center.getX(), center.getY()
self.xmax, self.xmin = x+w, x-w
self.ymax, self.ymin = y+h, y-h
p1 = Point(self.xmin, self.ymin)
p2 = Point(self.xmax, self.ymax)
self.rect = Rectangle(p1,p2)
self.rect.setFill('white')
self.rect.draw(win)
self.label = Text(center, label)
self.label.draw(win)
self.deactivate()
def clicked(self,p):
"Returns true if button active and p is inside."
return (self.active and self.xmin <= p.getX() <= self.xmax and self.ymin <= p.getY() <= self.ymax)
def getLabel(self):
"returns the label string of this button."
return self.label.geText()
def activate(self):
"sets this button to 'active'."
self.label.setFill('black')
self.rect.setWidth(2)
self.active = True
def deactivate(self):
"sets this button to 'inactive'."
self.label.setFill('lightgrey')
self.rect.setWidth(1)
self.active = False
class InputDialog: # Creates the input box. From Zelle.
""" A custom window for getting simulation values (angle, velocity, and height) from the user"""
def __init__(self, angle, vel, height):
""" Build and display the input window"""
self.win = win = GraphWin("Initial values", 200, 300,)
win.setCoords(0,4.5,4,.5)
Text(Point(1,1), "Angle").draw(win)
self.angle = Entry(Point(3,1),5).draw(win)
self.angle.setText(str(angle))
Text(Point(1,2), "velocity").draw(win)
self.vel = Entry(Point(3,2), 5).draw(win)
self.vel.setText(str(vel))
Text(Point(1,3), "Height").draw(win)
self.height = Entry(Point(3,3), 5).draw(win)
self.height.setText(str(height))
self.fire = Button(win, Point(1,4), 1.25, .5, "Fire!")
self.fire.activate()
self.quit = Button(win, Point(3,4), 1.25, .5, "Quit")
self.quit.activate()
def interact(self):
while True:
pt = self.win.getMouse()
if self.quit.clicked(pt):
return "Quit"
if self.fire.clicked(pt):
return "Fire!"
def getValues(self):
a = float(self.angle.getText())
v = float(self.vel.getText())
h = float(self.height.getText())
return a, v, h
def close(self):
self.win.close()
#class cup:
#def __init__():
#self.diameter = 15 # diameter of the cup
# self.irand = rand(0,200) # creates the cup randomly on the x axis
#self.startX = irand # startX is the starting position of the cup on the axis
#self.endX = irand + diameter # end of the cup on the x axis ( start plus diameter)
# self.startXinner = self.startX + 1 # rim
# self.endXinnner = self.endX - 1 # rim
#def collision(x_pos): # logical queries for the cup
# if (x_pos < self.startX): # ball doesnt hit rim equals false
# return False
# elif (x_pos > self.endX): # ball goes past cup equals false
# return False
# elif (x_pos >= self.startX and x_pos <= self.startXinner): # ball bounces off rim
# return False
# elif (x_pos >= self.endXinner and x_pos <= self.endX): # ball bounces off end rim
# return False
# else:
# return True # if everything else is false, ball must be inside the cup equals true
# main file to execute everything
class polygon:
def shape():
cup = turtle.pen()
cup.forward(15)
cup.right(90)
cup.backward(20)
cup.right(90)
cup.up()
cup.forward(15)
cup.left(90)
cup.down()
cup.forward(20)
def main():
win = GraphWin("Welcome To Raj's Cup Pong Game!", 640, 480, autoflush=False)
win.setCoords(-10,-10,210,155)
Line(Point(-10,0), Point(210,0)).draw(win)
for x in range(0,210,50):
Text(Point(x,-5), str(x)).draw(win)
angle, vel, height = 45.0, 40.0, 2.0 # The default values which are preset in the input box.
# cuplist = [] # creates an empty list to store cups in
#for k in range(0,5): # range of cups
#shape.append(shape()) # appends cups in random order
while True:
inputwin = InputDialog(angle, vel, height)
choice = inputwin.interact()
inputwin.close()
if choice == "Quit":
break
angle, vel, height = inputwin.getValues()
shot = shottracker(win, angle, vel, height)
while 0 <= shot.getY() and -10 < shot.getX() <= 210:
shot.update(1/50)
update(50)
main()
加载相关的Jupyter扩展名
(请参见https://rpy2.github.io/doc/v3.2.x/html/interactive.html#usage)
答案 2 :(得分:0)
如果仅使用Jupyter,只需确保运行
local.ERROR: Call to undefined method App\Pivots\Payables::setMorphType() {"userId":1,"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method App\\Pivots\\Payables::setMorphType() at /var/www/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50)
在单独的单元格中,请勿在{{1}}上方添加任何代码-甚至不添加#条注释。
所以正确的用法是:
单元格1:
%%R -i v
print(v)
单元2:
%%R
如果将所有内容放在同一个单元格中,将无法正常工作。
这不起作用:
%load_ext rpy2.ipython
v = 2
%%R -i v
print(v)
我认为原因与here中解释的原因相同。